dplyr을 사용하여 각 그룹에서 최대 값을 가진 행을 선택하는 방법은 무엇입니까? [복제]
이 질문에 이미 답변이 있습니다.
dplyr로 각 그룹에서 최대 값을 가진 행을 선택하고 싶습니다.
먼저 내 질문을 보여주기 위해 임의의 데이터를 생성합니다.
set.seed(1)
df <- expand.grid(list(A = 1:5, B = 1:5, C = 1:5))
df$value <- runif(nrow(df))
plyr에서 사용자 지정 함수를 사용하여이 행을 선택할 수 있습니다.
library(plyr)
ddply(df, .(A, B), function(x) x[which.max(x$value),])
dplyr에서는이 코드를 사용하여 최대 값을 얻지 만 최대 값을 가진 행 (이 경우 C 열)을 가져 오지 않습니다.
library(dplyr)
df %>% group_by(A, B) %>%
summarise(max = max(value))
어떻게 이걸 달성 할 수 있을까요? 제안 해 주셔서 감사합니다.
sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252
[3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C
[5] LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.2 plyr_1.8.1
loaded via a namespace (and not attached):
[1] assertthat_0.1.0.99 parallel_3.1.0 Rcpp_0.11.1
[4] tools_3.1.0
이 시도:
result <- df %>%
group_by(A, B) %>%
filter(value == max(value)) %>%
arrange(A,B,C)
작동하는 것 같습니다 :
identical(
as.data.frame(result),
ddply(df, .(A, B), function(x) x[which.max(x$value),])
)
#[1] TRUE
주석에서 @docendo가 지적했듯이 그룹당 slice
1 개의 행만 원하는 경우 아래 @RoyalITS의 답변에 따라 여기에서 선호 할 수 있습니다. 이 대답은 최대 값이 동일한 여러 행이있는 경우 여러 행을 반환합니다.
You can use top_n
df %>% group_by(A, B) %>% top_n(n=1)
This will rank by the last column (value
) and return the top n=1
rows.
Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)
df %>% group_by(A,B) %>% slice(which.max(value))
This more verbose solution provides greater control on what happens in case of duplicate maximum value (in this example, it will take one of the corresponding rows randomly)
library(dplyr)
df %>% group_by(A, B) %>%
mutate(the_rank = rank(-value, ties.method = "random")) %>%
filter(the_rank == 1) %>% select(-the_rank)
More generally, I think you might want to get "top" of the rows that are sorted within a given group.
For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).
# Answering the question of getting row with max "value".
df %>%
# Within each grouping of A and B values.
group_by( A, B) %>%
# Sort rows in descending order by "value" column.
arrange( desc(value) ) %>%
# Pick the top 1 value
slice(1) %>%
# Remember to ungroup in case you want to do further work without grouping.
ungroup()
# Answering an extension of the question of
# getting row with the max value of the lowest "C".
df %>%
# Within each grouping of A and B values.
group_by( A, B) %>%
# Sort rows in ascending order by C, and then within that by
# descending order by "value" column.
arrange( C, desc(value) ) %>%
# Pick the one top row based on the sort
slice(1) %>%
# Remember to ungroup in case you want to do further work without grouping.
ungroup()
For me, it helped to count the number of values per group. Copy the count table into a new object. Then filter for the max of the group based on the first grouping characteristic. For example:
count_table <- df %>%
group_by(A, B) %>%
count() %>%
arrange(A, desc(n))
count_table %>%
group_by(A) %>%
filter(n == max(n))
or
count_table %>%
group_by(A) %>%
top_n(1, n)
'development' 카테고리의 다른 글
VBA-for 루프 반복을 조건부로 건너 뛰는 방법 (0) | 2020.08.24 |
---|---|
Python 모듈 os.chmod (file, 664)는 권한을 rw-rw-r로 변경하지 않지만 -w--wx ---- (0) | 2020.08.24 |
jQuery-잘못된 호출 (0) | 2020.08.24 |
Stackpanel에 ScrollBar를 추가하는 방법 (0) | 2020.08.24 |
로컬 컴퓨터의 Windows 서비스가 시작된 후 중지됨 오류 (0) | 2020.08.24 |