keepfrog
keepfrog

Reputation: 136

purrr::map does not work with pipe operator

I have a data frame like this:

df <- tibble(
  i = rep(1:10, times = 5),
  t = rep(1:5, each = 10)
  ) %>% 
  mutate(y = rnorm(50))

I want to apply a function that takes data frame of each t as argument:

f <- function(df){
  return(lm(y ~ +1, data = df))
}

When I apply purrr::map for a nested data frame with pipe operator, I get error.

# does not work
df_nested <- df  %>% 
  nest(data = c(t, y)) %>% 
  rename(data_col = data) 

df_nested %>% 
  purrr::map(.x = .$data_col, .f = f)

On the other hand, when I do not use pipe operator, I get the desired result.

# Ok
purrr::map(.x = df_nested$data_col, .f = f)

To my understanding, both code should return the same result. What is wrong with the code with pipe operator?

Upvotes: 0

Views: 654

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

Pipe already passes the previous value (df_nested) as the first argument to map. You may use {} to stop that from happening.

library(tidyverse)

df_nested %>% 
  {purrr::map(.x = .$data_col, .f = f)}

Another way would be to use -

df  %>% 
  nest(data_col = c(t, y)) %>%
  mutate(model = map(data_col, f))

#      i data_col         model 
#   <int> <list>           <list>
# 1     1 <tibble [5 × 2]> <lm>  
# 2     2 <tibble [5 × 2]> <lm>  
# 3     3 <tibble [5 × 2]> <lm>  
# 4     4 <tibble [5 × 2]> <lm>  
# 5     5 <tibble [5 × 2]> <lm>  
# 6     6 <tibble [5 × 2]> <lm>  
# 7     7 <tibble [5 × 2]> <lm>  
# 8     8 <tibble [5 × 2]> <lm>  
# 9     9 <tibble [5 × 2]> <lm>  
#10    10 <tibble [5 × 2]> <lm>  

Upvotes: 3

Related Questions