Search code examples
rdictionarypurrrspread

Perform spread on nested data frame


I'd like to perform spread on a nested data frame but can't work it out. Here's a toy data frame for using spread on a normal data frame:

df <- data.frame( A = 1:4, B = 5:8)
df %>% spread(A,B)

  1 2 3 4
1 5 6 7 8

Here's a toy example for a nested data frame and what I've tried (but doesn't work):

df <- data.frame( dummy=c(1,1,2,2), A = 1:4, B = 5:8)
df %>% 
   nest(-dummy) %>% 
   mutate(data = map(data, ~spread(.x$A,.x$B)))

Error in mutate_impl(.data, dots) : 
   Evaluation error: Invalid column specification.

Thanks for any help!


Solution

  • df <- data.frame( dummy=c(1,1,2,2), A = 1:4, B = 5:8)
    df %>% 
      nest(-dummy) %>% 
      mutate(data = map(data, ~spread(.x, key = A, value = B)))