I have messy-looking data where multiple columns have multiple comma-separated values:
df <- data.frame(
Line = 1:2,
Utterance = c("hi there", "how're ya"),
A_aoi = c("C*B*C", "*"),
A_aoi_dur = c("100,25,30,50,144", "200"),
B_aoi = c("*A", "*A*A*C"),
B_aoi_dur = c("777,876", "50,22,33,100,150,999")
)
What I'd like to do is pivot_longer so that each of the comma-separated values has their own row. I can accomplish this but it seems the way I'm accomplishing is anything but accomplished as it involves multiple intermediary steps and temporary dfs making the code long-winded and heavy:
library(dplyr)
library(tidyr)
# first temporary `df`:
df1 <- df %>%
select(-ends_with("dur")) %>%
pivot_longer(cols = ends_with("aoi"),
names_to = "Speaker") %>%
separate_rows(value, sep = "(?!^|$)") %>%
mutate(Speaker = sub("^(.).*", "\\1", Speaker)) %>%
rename(AOI = value)
# second temporary `df`:
df2 <- df %>%
select(-ends_with("aoi")) %>%
pivot_longer(cols = ends_with("dur")) %>%
separate_rows(value, sep = ",") %>%
rename(Dur = value)
# final `df` (aka, the **expected outcome**):
df3 <- cbind(df1, df2[,4])
df3
Line Utterance Speaker AOI Dur
1 1 hi there A C 100
2 1 hi there A * 25
3 1 hi there A B 30
4 1 hi there A * 50
5 1 hi there A C 144
6 1 hi there B * 777
7 1 hi there B A 876
8 2 how're ya A * 200
9 2 how're ya B * 50
10 2 how're ya B A 22
11 2 how're ya B * 33
12 2 how're ya B A 100
13 2 how're ya B * 150
14 2 how're ya B C 999
How can this transfomation be achieved more succintly?