student <- data.frame(ID = c(11, 12, 13),
Name = c("Devin", "Edward", "Wenli"),
Gender = c("M", "M", "F"),
Birthdate = c("1984-12-29", "1983-5-6", "1986-8-8"))
selection <- c("Name", "Gender", "Birthdate")
现在我想编写一个循环
library(dplyr)
for(choice in selection){
df = group_by(choice)
print(df)
}
但是它不起作用。我该怎么办?
答案 0 :(得分:0)
也许这就是你所追求的?
library(dplyr)
for(choice in selection){
student %>% group_by(!!choice ) %>% print()
}
# A tibble: 3 x 5 # Groups: "Name" [1] ID Name Gender Birthdate `"Name"` <dbl> <fct> <fct> <fct> <chr> 1 11.0 Devin M 1984-12-29 Name 2 12.0 Edward M 1983-5-6 Name 3 13.0 Wenli F 1986-8-8 Name # A tibble: 3 x 5 # Groups: "Gender" [1] ID Name Gender Birthdate `"Gender"` <dbl> <fct> <fct> <fct> <chr> 1 11.0 Devin M 1984-12-29 Gender 2 12.0 Edward M 1983-5-6 Gender 3 13.0 Wenli F 1986-8-8 Gender # A tibble: 3 x 5 # Groups: "Birthdate" [1] ID Name Gender Birthdate `"Birthdate"` <dbl> <fct> <fct> <fct> <chr> 1 11.0 Devin M 1984-12-29 Birthdate 2 12.0 Edward M 1983-5-6 Birthdate 3 13.0 Wenli F 1986-8-8 Birthdate
请注意,OP仅请求group_by()
,而不是summarize()
。
!!
运算符的解释Programming with dplyr上的小插图说:
在dplyr中(通常在tidyeval中)使用!!说你想要 取消引用的引用,以便对其进行评估,而不引用。