我想使用dplyr将表分组为一列,然后将函数应用于每组第二列中的值集.
例如,在下面的代码示例中,我想返回每个人吃的所有2项食物组合.我无法弄清楚如何在功能中正确提供功能与正确的列(食物)do()
.
library(dplyr)
person = c( 'Grace', 'Grace', 'Grace', 'Rob', 'Rob', 'Rob' )
foods = c( 'apple', 'banana', 'cucumber', 'spaghetti', 'cucumber', 'banana' )
eaten = data.frame(person, foods)
by_person = group_by(eaten, person)
# How to do this?
do( by_person, combn( x = foods, m = 2 ) )
Run Code Online (Sandbox Code Playgroud)
请注意,?do
我的计算机上的示例代码失败
mods <- do(carriers, failwith(NULL, lm), formula = ArrDelay ~ date)
Run Code Online (Sandbox Code Playgroud) 我必须遗漏一些关于如何剥离group_by
水平的东西dplyr
.在下面的示例中,我将2列分组,将值汇总到单个变量中,然后按该新变量排序:
mtcars %>% group_by( cyl, gear ) %>%
summarize( hp_range = max(hp) - min(mpg)) %>%
arrange( desc(hp_range) )
# Source: local data frame [8 x 3]
# Groups: cyl [3]
#
# cyl gear hp_range
# (dbl) (dbl) (dbl)
#1 4 4 87.6
#2 4 5 87.0
#3 4 3 75.5
#4 6 5 155.3
#5 6 4 105.2
#6 6 3 91.9
#7 8 5 320.0
#8 8 3 234.6
Run Code Online (Sandbox Code Playgroud)
显然这不按hp_range
预期排序.我错过了什么?
编辑:该示例按预期工作,没有desc …