简体   繁体   English

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

[英]Code not working using map from purrr package in R

I'm learning the map function in purrr package and have the following code not working: 我正在学习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)

For the last two block of code, the errors return as: 对于最后两个代码块,错误返回为:

Error: Index 1 must have length 1 错误:索引1的长度必须为1

By contrary, the following two blocks of code work well, 相反,以下两个代码块运行良好,

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))

Can anyone help me to understand the errors and how to fix them? 任何人都可以帮助我理解错误以及如何解决它们?

You need to add braces around the map expression, since . 您需要在map表达式周围添加大括号,因为. doesn't appear as a separate argument placeholder in the function so magrittr pipe is applying the first-argument rule which you can read more about here ; 在函数中不会显示为单独的参数占位符,因此magrittr管道正在应用第一个参数规则 ,您可以在此处阅读更多信息; and also use ~ to construct a function which is what map is expecting: 并使用~来构造一个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

Similarly for the second method: 类似地,第二种方法:

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

If you wanted to use split() , I usually split on my grouping factor and then just map an anonymous function for what I want to do for a single tibble/dataframe in the newly created list: 如果你想使用split() ,我通常会分割我的分组因子,然后只为我想要为新创建的列表中的单个tibble / dataframe做的事情映射一个匿名函数:

df1 %>% 
    split(.$type1) %>% 
    map(~ mutate(., z = x + y) %>% # chain like you would a single tib
        select(z) %>%
        unlist(T,F))
$a
[1] 12 14 16 18 20

$b
[1] 22 24 26 28 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM