我有如下所示的數據幀:dplyr:組中的最大值,不包括每行中的值?
> df <- data_frame(g = c('A', 'A', 'B', 'B', 'B', 'C'), x = c(7, 3, 5, 9, 2, 4))
> df
Source: local data frame [6 x 2]
g x
1 A 7
2 A 3
3 B 5
4 B 9
5 B 2
6 C 4
我知道如何與最大x
值加列各組g
:
> df %>% group_by(g) %>% mutate(x_max = max(x))
Source: local data frame [6 x 3]
Groups: g
g x x_max
1 A 7 7
2 A 3 7
3 B 5 9
4 B 9 9
5 B 2 9
6 C 4 4
但我想是得到的是每個組的最大值x
的值g
,不包括x
的值,每行。
對於給定的例子中,所需的輸出應該是這樣的:
Source: local data frame [6 x 3]
Groups: g
g x x_max x_max_exclude
1 A 7 7 3
2 A 3 7 7
3 B 5 9 9
4 B 9 9 5
5 B 2 9 9
6 C 4 4 NA
我想我可能能夠使用row_number()
刪除特定的元素,並採取了什麼仍然是最大的,但命中警告消息和得到不正確-Inf
輸出:
> df %>% group_by(g) %>% mutate(x_max = max(x), r = row_number(), x_max_exclude = max(x[-r]))
Source: local data frame [6 x 5]
Groups: g
g x x_max r x_max_exclude
1 A 7 7 1 -Inf
2 A 3 7 2 -Inf
3 B 5 9 1 -Inf
4 B 9 9 2 -Inf
5 B 2 9 3 -Inf
6 C 4 4 1 -Inf
Warning messages:
1: In max(c(4, 9, 2)[-1:3]) :
no non-missing arguments to max; returning -Inf
2: In max(c(4, 9, 2)[-1:3]) :
no non-missing arguments to max; returning -Inf
3: In max(c(4, 9, 2)[-1:3]) :
no non-missing arguments to max; returning -Inf
什麼是最{可讀性,簡潔,高效}辦法讓dplyr這個輸出?任何洞察到爲什麼我的嘗試使用row_number()
不起作用也將不勝感激。謝謝您的幫助。
這是代碼:總結(GROUP_BY(DF,G),max.x = MAX(X ))? –
謝謝,@陳盛林,但這不符合上述示例中的所需輸出。這給了我每個組的最大'x'值(返回一個3行的data_frame)。但我想要的是具有與輸入表相同行數的data_frame,其中行'r'處的值給出'g'組中的最大'x'值,不包括行'r'。有關具體示例,請參閱上面的「所需輸出」。 – Eric