I am looking to tidy a nested data frame and I'm having some difficulties. I can reshape the data fine using one case, but I am looking to iterate over the entire data frame by case.
My data looks like this:
df <- tibble(
case = c("a","a","b","b","c","c"),
year = c(1990,2000,1990,2000,1990,2000),
var1 = round(runif(6,0,1), 2),
var2 = round(runif(6,10,20), 2)
)
I can perform the task I would like to with only one case using tidyr
df %>%
filter( case == "a") %>%
gather(var, value, -c(1:2)) %>%
spread(year, value)
Output:
# case var `1990` `2000`
# <chr> <chr> <dbl> <dbl>
# 1 a var1 0.850 0.540
# 2 a var2 14.4 16.7
How can I use purrr or another functional programming tool to vectorize this operation and perform the same action with all of my cases and bind them into one data frame? Some combination of "nest" and "map"?
Thank you!
df %>% nest(-case) %>% mutate(output = map(data, ~gather(.x, var, val, -year) %>% spread(year, val))) %>% unnest(), but it seems like there's a more elegant way to write that - alistairedf %>% gather(var, val, var1:var2) %>% spread(year, val)- alistaire