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:
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?