【发布时间】:2018-12-09 02:42:02
【问题描述】:
我想在 dplyr 函数中创建一个简单的 if/else 条件。我查看了一些有用的帖子(例如,How to parametrize function calls in dplyr 0.7?),但仍然遇到问题。
下面是一个玩具示例,当我调用函数 没有 分组变量时,它可以工作。然后该函数因分组变量而失败。
# example dataset
test <- tibble(
A = c(1:5,1:5),
B = c(1,2,1,2,3,3,3,3,3,3),
C = c(1,1,1,1,2,3,4,5,4,3)
)
# begin function, set default for group var to NULL.
prop_tab <- function(df, column, group = NULL) {
col_name <- enquo(column)
group_name <- enquo(group)
# if group_by var is NOT null, then...
if(!is.null(group)) {
temp <- df %>%
select(!!col_name, !!group_name) %>%
group_by(!!group_name) %>%
summarise(Percentages = 100 * length(!!col_name) / nrow(df))
} else {
# if group_by var is null, then...
temp <- df %>%
select(!!col_name) %>%
group_by(col_name = !!col_name) %>%
summarise(Percentages = 100 * length(!!col_name) / nrow(df))
}
temp
}
test %>% prop_tab(column = C) # works
test %>% prop_tab(column = A, group = B) # fails
# Error in prop_tab(., column = A, group = B) : object 'B' not found
【问题讨论】:
标签: r function if-statement dplyr