0

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.

Eric Canton
  • 324
  • 2
  • 10
  • Does this answer your question? [Split text string in a data.table columns](https://stackoverflow.com/questions/18154556/split-text-string-in-a-data-table-columns) – MattB Aug 19 '20 at 16:36

1 Answers1

2

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
YOLO
  • 20,181
  • 5
  • 20
  • 40
  • This is fantastic, just what I was hoping could be done. Thank you! One little modifcation: `lapply(.SD, strsplit, split=",")` should be replaced with `lapply(.SD, function(x) strsplit(x, split=","))` I think, since `lapply` doesn't handle currying for us (at least not in the version of R I'm using, 3.6.1). – Eric Canton Aug 19 '20 at 16:44