I'm looking for an R data.table
equivalent to: converting multiple comma separated columns into rows (SQL)
It's okay with me if only one column can be handled at a time.
I'm looking for an R data.table
equivalent to: converting multiple comma separated columns into rows (SQL)
It's okay with me if only one column can be handled at a time.
Here's a way:
# get last two column names
cols=names(df)[-1]
# convert columns to list
df[,(cols) := lapply(.SD, strsplit, split=','), .SDcols=cols]
# explode the list
dfnew = df[, lapply(.SD, unlist), by=1:nrow(df)]
dfnew[, nrow:=NULL]
print(dfnew)
Id Column1 Column2
1: 1 A H
2: 1 B H
3: 1 C H
4: 2 D J
5: 2 E K
6: 3 F L
7: 3 F M
8: 3 F N