Search code examples
rstrsplit

R Splitting the column into 2 with out changing other columns


I have my input. I am using R. I want solution in R

    id       places         present   
   1234    |new|world|life   yes
   5111      
 2012222   |lamp             yes
 123333    |world11|ness     yes    

I want output

      id       places         present   
   1234        new            y9970s
   1234        world          7655s
   1234        life           54644s
   5111      
2012222        lamp           y777s
 123333        world11        y998s
 123333        ness           y99s

I have tried

dt <- data.table(input)
dt=dt[ , list( V3 = unlist( strsplit(as.character( V3),"\\|") ) ) , by = V1]

but the 3rd column is left out. Even if I have multiple columns in that case how will I work


Solution

  • A possible solution with the data.table package:

    library(data.table)
    dt <- data.table(df)
    new.dt <- dt[,strsplit(as.character(places),"|",fixed=TRUE), by=list(id,present)]