我正在学习 purrr 包中的 map 功能,并且以下代码不起作用:
library(purrr)
library(dplyr)
df1 = data.frame(type1 = c(rep('a',5),rep('b',5)),
x = 1:10,
y = 11:20)
df1 %>%
group_by(type1) %>%
nest() %>%
map(.$data,with(.x, x + y))
df1 %>%
group_by(type1) %>%
nest() %>%
map(.$data,function(df) df$x + df$y)
对于最后两个代码块,错误返回为:
Error: Index 1 must have length 1
相反,以下两个代码块运行良好,
df1 %>%
group_by(type1) %>%
nest() %>% .$data %>%
map(.,~with(.x, .x$x + .x$y))
df1 %>%
group_by(type1) %>%
nest() %>% .$data %>%
map(.,~with(.x, .x$x + .x$y))
谁能帮我理解错误以及如何解决它们?
最佳答案
您需要在 map
周围添加大括号表达式,因为 .
不会在函数中显示为单独的参数占位符,因此 magrittr 管道正在应用第一个参数规则,您可以阅读有关 here 的更多信息;并使用 ~
构造一个函数,它是 map
期待:
df1 %>%
group_by(type1) %>%
nest() %>%
{ map(.$data, ~ with(.x, x + y)) }
#[[1]]
#[1] 12 14 16 18 20
#[[2]]
#[1] 22 24 26 28 30
第二种方法类似:
df1 %>%
group_by(type1) %>%
nest() %>%
{ map(.$data,function(df) df$x + df$y) }
#[[1]]
#[1] 12 14 16 18 20
#[[2]]
#[1] 22 24 26 28 30
关于r - 代码无法使用 R 中 purrr 包中的 map 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009016/