dplyr 的最新版本不推荐使用下划线版本的函数,例如 filter_,而支持tidy evaluation。
下划线形式的新形式是什么预期的新形式?如何使用 R CMD 检查避免未定义的符号?
library(dplyr)
df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
df %>% filter_(~id == "a")
# want to avoid this, because it references column id in a variable-style
df %>% filter( id == "a" )
# option A
df %>% filter( UQ(rlang::sym("id")) == "a" )
# option B
df %>% filter( UQ(as.name("id")) == "a" )
# option C
df %>% filter( .data$id == "a" )
是否有首选或更深思熟虑的形式?选项 C 最短,但在我的一些真实世界较大的数据集和更复杂的 dplyr 构造上速度较慢:
microbenchmark(
sym = dsPClosest %>%
group_by(!!sym(dateVarName), !!sym("depth")) %>%
summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
, moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
ungroup()
,data = dsPClosest %>%
group_by(!!sym(dateVarName), .data$depth ) %>%
summarise(temperature = mean(.data$temperature , na.rm = TRUE)
, moisture = mean(.data$moisture , na.rm = TRUE)) %>%
ungroup()
,times=10
)
#Unit: milliseconds
# expr min lq mean median uq max neval
# sym 80.05512 84.97267 122.7513 94.79805 100.9679 392.1375 10
# data 4652.83104 4741.99165 5371.5448 5039.63307 5471.9261 7926.7648 10
mutate_使用更复杂的语法还有另一个答案。