我正在尝试学习如何在
purrr
(& dplyr
) 函数中使用 NSE。
案例 1) 有“解散”组变量并且它有效。情况 2) 已“解除”数值变量,但它不起作用。我不太明白警告消息“参数不是数字或逻辑:返回 NA”。
这是一个可重现的示例:
library(dplyr)
library(purrr)
# CASE 1) works!
group_var <- c("gender", "species")
NSE_map_g <- map(.x = group_var,
.f = ~{
starwars %>%
group_by( {{.x}}) %>%
summarise(mean_height = mean(height , na.rm = TRUE ))
})
pluck(NSE_map_g,1)
这是有问题的案例:
# CASE 2) DOESN'T work!
num_var <- c("height", "birth_year")
NSE_map_n <- map(.x = num_var,
.f = ~{
starwars %>%
group_by(species) %>%
summarise("mean_{{.x}}" := mean({{.x}}, na.rm = TRUE ))
})
pluck(NSE_map_n,1)
我认为这给了你你想要的。您需要给
map
一个符号向量,而不是字符。
NSE_map_n <- map(.x = vars(height, birth_year),
.f = ~{
starwars %>%
group_by(species) %>%
summarise("mean_{{.x}}" := mean({{.x}}, na.rm = TRUE ))
})
NSE_map_n
[[1]]
# A tibble: 38 × 2
species mean_height
<chr> <dbl>
1 Aleena 79
2 Besalisk 198
3 Cerean 198
4 Chagrian 196
5 Clawdite 168
6 Droid 131.
7 Dug 112
8 Ewok 88
9 Geonosian 183
10 Gungan 209.
# ℹ 28 more rows
# ℹ Use `print(n = ...)` to see more rows
[[2]]
# A tibble: 38 × 2
species mean_birth_year
<chr> <dbl>
1 Aleena NaN
2 Besalisk NaN
3 Cerean 92
4 Chagrian NaN
5 Clawdite NaN
6 Droid 53.3
7 Dug NaN
8 Ewok 8
9 Geonosian NaN
10 Gungan 52
# ℹ 28 more rows
# ℹ Use `print(n = ...)` to see more rows