0

I have a data like this

> a<-data.table(col1=c(1,2,3),col2=c("1;2","11;22","111;333"))
> a
   col1    col2
1:    1     1;2
2:    2   11;22
3:    3 111;333

and I want to get it to the following format

   col1    col2  
1:    1     1
2:    2     11
3:    3     111
4:    1     2
5:    2     22
6:    3     333

for which something like a %>% mutate(col1=strplit(...,";"), col2=strplit(...,";")) should work in a dplyr/tidyr way for data.frame but now data.table.

How to transform a data.table like the above by splitting the values?

hhh
  • 50,788
  • 62
  • 179
  • 282

1 Answers1

1

We can group by 'col1' and split the 'col2' with strsplit

library(data.table)
a[, .(col2 = unlist(strsplit(col2, ';'))),col1]

Or with splitstackshape using cSplit

library(splitstackshape)
cSplit(a, 'col2', ';', 'long')

Or with tidyverse using separate_rows

library(tidyverse)
separate_rows(a, col2)
akrun
  • 874,273
  • 37
  • 540
  • 662