我正在学习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)
Run Code Online (Sandbox Code Playgroud)
对于最后两个代码块,错误返回为:
错误:索引1的长度必须为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))
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我理解错误以及如何解决它们?
你需要在map
表达式周围添加大括号,因为.
它不会在函数中显示为单独的参数占位符,所以magrittr管道正在应用第一个参数规则,你可以在这里阅读更多信息; 并且还用于~
构造一个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
Run Code Online (Sandbox Code Playgroud)
类似地,第二种方法:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2067 次 |
最近记录: |