I've got some time series data where both the steps of the sequence (ranging from 1 to 8) as well as its topic (>100) are encoded as character factor levels within a single variable. Here is a minimal example (I omitted timestamps which would be increasing within each id):
id <- c(1,rep(2,5),rep(3,4))
step <- c("call", "call", "agent", "forest", "forward", "resolved", "call", "agent", "beach", "resolved")
(df <- data.frame(id,step))
id step
1 1 call
2 2 call
3 2 agent
4 2 forest
5 2 forward
6 2 resolved
7 3 call
8 3 agent
9 3 beach
10 3 resolved
I now want to split this information into two dedicated variables (step and topic), thereby shrinking the dataframe in rows and making it wider, while also repeating the topic for each row of the time series and adding an "NA" when there is no topic. Using base R to split this into two dataframes and merging them back together gets the job done:
step <- subset(df, step %in% c("call", "agent", "forward", "resolved"))
topic <- subset(df, step %in% c("forest", "beach"))
topic$topic <- topic$step
topic$step <- NULL
(newdf <- merge(step,topic, all=TRUE))
id step topic
1 1 call <NA>
2 2 call forest
3 2 agent forest
4 2 forward forest
5 2 resolved forest
6 3 call beach
7 3 agent beach
8 3 resolved beach
This is somewhat clunky though and I'm looking for a more elegant dplyr/tidyverse approach to this. pivot_wider() doesn't seem to be able to do this. Any ideas?