代码无法使用R中的purrr包中的映射

Jas*_*son 4 r dplyr purrr

我正在学习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)

任何人都可以帮助我理解错误以及如何解决它们?

Psi*_*dom 6

你需要在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)

  • 没有`{}`,你的代码相当于`map(.,.$ data,~with(.x,x + y))`由于第一个参数规则,这是`map`函数的错误语法.此外,你是如何得到"lapply"工作的?在我看来,你仍然需要支撑"lapply"才能正常工作; (2认同)