Skip to content

Instantly share code, notes, and snippets.

@tmastny
Created June 4, 2019 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmastny/daf4f0a97bc84c7f01d3648e38b7774b to your computer and use it in GitHub Desktop.
Save tmastny/daf4f0a97bc84c7f01d3648e38b7774b to your computer and use it in GitHub Desktop.
Spread and pivot over multiple columns
library(tidyverse)
test <- crossing(
teamid = c(1, 2, 3),
action = c("a", "b", "c")
)
test <- test %>%
group_by(action) %>%
mutate(
day30 = c(10, 20, 30),
day60 = c(15, 25, 35),
day90 = c(20, 30, 40)
) %>%
ungroup()
test
test %>%
gather(days, count, day30:day90) %>%
unite(temp, days, action) %>%
spread(temp, count)
test %>%
pivot_longer(day30:day90, names_to = "days")
test %>%
pivot_longer(day30:day90, names_to = "days") %>%
pivot_wider(names_from = c(days, action))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment