使用R中purrr包中的map的代码不起作用 [英] Code not working using map from purrr package in R
问题描述
我正在学习purrr包中的map函数,并且下面的代码不起作用:
I'm learning the map function in purrr package and have the following code not working:
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:
错误:索引1的长度必须为1
Error: Index 1 must have length 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?
推荐答案
您需要在<$ c周围添加括号$ c> map 表达式,因为。
不会在函数中显示为单独的参数占位符,因此 magrittr 管道正在应用第一参数规则,您可以在此处了解更多信息;并且还使用〜
构造一个函数,该函数正是 map
所期望的:
You need to add braces around the map
expression, since .
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; and also use ~
to construct a function which is what map
is expecting:
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
这篇关于使用R中purrr包中的map的代码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!