I'm trying to reshape my data from long to wide, but here I need to create names column such as event1, event2, event3, etc. In other words, there's no natural candidate for names_from
argument. I've tried a couple of different ways but cannot get what I'm looking for- Here's a reproducible example.
set.seed(57)
df <- data.frame(date = seq.Date(as.Date("2009-01-01"), as.Date("2009-01-12"), by = 1),
id = rep(1:3, each = 4),
val = rnorm(12)) %>% filter(val > 0.5)
I want to convert df
to df2
.
df2 <- data.frame(id = c(1:3),
event1 = c("2009-01-03", "2009-01-06", "2009-01-10"),
event2 = c("2009-01-04", "2009-01-07", "2009-01-11"),
event3 = c(" ", " ", "2009-01-12"))
Note that this data set documents the first, second, and third (if any) occurrence date for each id.
Here's what I've tried using names_prefix
but doesn't seem to work.
set.seed(57)
df <- data.frame(date = seq.Date(as.Date("2009-01-01"), as.Date("2009-01-12"), by = 1),
id = rep(1:3, each = 4),
val = rnorm(12)) %>% filter(val > 0.5) %>%
pivot_wider(names_prefix = "event", names_from = val, values_from = date)