我想用 purrr
遍历一个变量名向量,然后用 dplyr
在函数内使用变量,如下面的代码:
library(dplyr)
library(purrr)
#creating index
index<-c('Sepal.Length', 'Sepal.Width')
#mapping over index with lambda function
map(index, ~iris %>% filter (.x > mean(.x)))
我期待看到两个 data.frames 的列表,如
list(Sepal.Length = iris %>% filter (Sepal.Length > mean(Sepal.Length)),
Sepal.Width = iris %>% filter (Sepal.Width > mean(Sepal.Width)))
有没有办法在 lambda 函数的 data.frames 中使用 .x
变量作为列名?
我认为这可能与数据屏蔽和非标准评估有关,我怀疑 rlang
在这里可能会有帮助,但我不熟悉这个主题。
谢谢
最佳答案
那些是字符串。我们需要转换为 sym
bol 并求值 (!!
)
library(purrr)
library(dplyr)
out <- map(index, ~iris %>%
filter (!! rlang::sym(.x) > mean(!! rlang::sym(.x))))
names(out) <- index
-输出
> str(out)
List of 2
$ Sepal.Length:'data.frame': 70 obs. of 5 variables:
..$ Sepal.Length: num [1:70] 7 6.4 6.9 6.5 6.3 6.6 5.9 6 6.1 6.7 ...
..$ Sepal.Width : num [1:70] 3.2 3.2 3.1 2.8 3.3 2.9 3 2.2 2.9 3.1 ...
..$ Petal.Length: num [1:70] 4.7 4.5 4.9 4.6 4.7 4.6 4.2 4 4.7 4.4 ...
..$ Petal.Width : num [1:70] 1.4 1.5 1.5 1.5 1.6 1.3 1.5 1 1.4 1.4 ...
..$ Species : Factor w/ 3 levels "setosa","versicolor",..: 2 2 2 2 2 2 2 2 2 2 ...
$ Sepal.Width :'data.frame': 67 obs. of 5 variables:
..$ Sepal.Length: num [1:67] 5.1 4.7 4.6 5 5.4 4.6 5 4.9 5.4 4.8 ...
..$ Sepal.Width : num [1:67] 3.5 3.2 3.1 3.6 3.9 3.4 3.4 3.1 3.7 3.4 ...
..$ Petal.Length: num [1:67] 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.5 1.5 1.6 ...
..$ Petal.Width : num [1:67] 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.1 0.2 0.2 ...
..$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
-按照 OP 的预期进行测试
> expected <- list(Sepal.Length = iris %>% filter (Sepal.Length > mean(Sepal.Length)),
+ Sepal.Width = iris %>% filter (Sepal.Width > mean(Sepal.Width)))
>
> identical(out, expected)
[1] TRUE
或使用 cur_data()
的子集
map(index, ~ iris %>%
filter(cur_data()[[.x]] > mean(cur_data()[[.x]])))
或者使用across
或者if_all
,直接取string
map(index, ~ iris %>%
filter(across(all_of(.x), ~ . > mean(.))))
关于r - 循环字符向量并使用元素作为 lambda 函数中的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68809685/