使用 mutate_each_ 控制 dplyr 评估范围
Controlling dplyr evaluation scope with mutate_each_
有没有办法确保 mutate_each_
(或者可能是 funs_
)在父框架中查找函数?考虑:
library(dplyr) # 0.4.1
library(magrittr) # 1.5
fun_list <- list(a=quote(rev), b=quote(sort))
iris[1:5, 1:2] %>% mutate_each_(funs_(fun_list), c("Sepal.Length"))
如您所愿工作:
Sepal.Length Sepal.Width a b
1 5.1 3.5 5.0 4.6
2 4.9 3.0 4.6 4.7
3 4.7 3.2 4.7 4.9
4 4.6 3.1 4.9 5.0
5 5.0 3.6 5.1 5.1
但是:
my_rev <- rev
my_srt <- sort
fun_list2 <- list(a=quote(my_rev), b=quote(my_srt))
iris[1:5, 1:2] %>% mutate_each_(funs_(fun_list2), c("Sepal.Length"))
错误:
Error in mutate_impl(.data, dots) : could not find function "my_rev"
一个简单的mutate
作品:
iris[1:5, 1:2] %>% mutate(a=my_rev(Sepal.Length), b=my_srt(Sepal.Length))
您应该在此处使用公式 ~
表示法而不是 quote()
my_rev <- rev
my_srt <- sort
fun_list2 <- list(a = ~my_rev, b = ~my_srt)
iris[1:5, 1:2] %>% mutate_each_(funs_(fun_list2), c("Sepal.Length"))
来自非标准评估小插图:
It’s best to use a formula, because a formula captures both the
expression to evaluate, and the environment in which it should be a
evaluated.
有没有办法确保 mutate_each_
(或者可能是 funs_
)在父框架中查找函数?考虑:
library(dplyr) # 0.4.1
library(magrittr) # 1.5
fun_list <- list(a=quote(rev), b=quote(sort))
iris[1:5, 1:2] %>% mutate_each_(funs_(fun_list), c("Sepal.Length"))
如您所愿工作:
Sepal.Length Sepal.Width a b
1 5.1 3.5 5.0 4.6
2 4.9 3.0 4.6 4.7
3 4.7 3.2 4.7 4.9
4 4.6 3.1 4.9 5.0
5 5.0 3.6 5.1 5.1
但是:
my_rev <- rev
my_srt <- sort
fun_list2 <- list(a=quote(my_rev), b=quote(my_srt))
iris[1:5, 1:2] %>% mutate_each_(funs_(fun_list2), c("Sepal.Length"))
错误:
Error in mutate_impl(.data, dots) : could not find function "my_rev"
一个简单的mutate
作品:
iris[1:5, 1:2] %>% mutate(a=my_rev(Sepal.Length), b=my_srt(Sepal.Length))
您应该在此处使用公式 ~
表示法而不是 quote()
my_rev <- rev
my_srt <- sort
fun_list2 <- list(a = ~my_rev, b = ~my_srt)
iris[1:5, 1:2] %>% mutate_each_(funs_(fun_list2), c("Sepal.Length"))
来自非标准评估小插图:
It’s best to use a formula, because a formula captures both the expression to evaluate, and the environment in which it should be a evaluated.