我需要根据条件按变量 x 或变量 y 进行分组。当我使用 magrittr 管道时,这不会发生。
考虑一个数据框 df1:
> df1
seat_id student_id seat_state
1 1222 500 9
2 850 500 9
3 850 500 9
4 1225 500 9
5 16502 500 9
6 17792 500 9
7 17792 500 9
8 1219 501 10
9 847 501 9
10 847 501 9
11 1220 501 9
12 17785 501 9
13 17785 501 9
14 1214 502 9
15 842 502 9
16 842 502 9
17 1215 502 9
18 1211 503 9
19 839 503 9
20 839 503 9
现在假设我想用两种方式总结一下 1. 按 student_id 或 2. 按座位状态 取决于变量
总结
古老而漫长的道路是
if (summary==1) df1 %>% group_by(student_id) %>% summarise(seats=n()) else if (summary==2) df1 %>% group_by(seat_state) %> % 总结(座位=n())
但必须有一种更紧凑的方式,特别是因为我在总结语句之后有几个 magrittr 管道,因此会使代码的大小加倍。
最佳答案
在最新版本的 dplyr
(0.7.1
) 中。我们可以使用 quo
和 unquote (!!
) 来传递分组变量。这是一个使用 dplyr
中的 quo
的函数示例。您可以键入 vignette("programming")
以了解更多信息。
# Load package
library(dplyr)
# Create a function
# This function has two arguments. The first one is the data frame
# The second one use to specify condition: 1 means group the student_id,
# while 2 means group the seat_state
my_summary <- function(df1, condition){
if (condition == 1){
group_var <- quo(student_id)
} else if (condition == 2){
group_var <- quo(seat_state)
}
df1 %>%
group_by(!!group_var) %>%
summarise(seats=n())
}
# Test the function
my_summary(df1, 1)
# A tibble: 4 x 2
student_id seats
<int> <int>
1 500 7
2 501 6
3 502 4
4 503 3
my_summary(df1, 2)
# A tibble: 2 x 2
seat_state seats
<int> <int>
1 9 19
2 10 1
关于r - 如何在 if-then-else 之类的条件下使用 group_by 并应用 dplyr 哲学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45114758/