如何使用if_ then-else之类的条件使用group_by并应用dplyr哲学

时间:2017-07-15 05:14:21

标签: r dplyr

我需要根据条件对变量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. 按seat_state 取决于变量

summary

旧的和漫长的方式是

if (summary==1) df1 %>% group_by(student_id) %>% summarise(seats=n()) else if (summary==2) df1 %>% group_by(seat_state) %>% summarise(seats=n())

但必须有一种更紧凑的方式,特别是因为我在汇总语句后面有几个magrittr管道,因此会使代码的大小加倍。

3 个答案:

答案 0 :(得分:1)

在最新版本的dplyr0.7.1)中。我们可以使用quo和unquote(!!)来传递分组变量。以下是使用quo中的dplyr的函数示例。您可以输入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

答案 1 :(得分:1)

我们可以通过对if/else list的{​​{1}}进行分项来替换quos

f1 <- function(df, cond) {
    grp <- quos(student_id, seat_state)[[cond]]      
    df %>%
        group_by(UQ(grp)) %>%
        summarise(seats = n())
}

f1(df1, 1)
# A tibble: 4 x 2
#  student_id seats
#       <int> <int>
#1        500     7
#2        501     6
#3        502     4
#4        503     3

f1(df1, 2)
# A tibble: 2 x 2
#  seat_state seats
#       <int> <int>
#1          9    19
#2         10     1

答案 2 :(得分:0)

my_col <- 1 # the column number
df1 %>% group_by(.[,my_col]) %>% summarise(seats=n())