r - How to separate values in a column and add them in a new row? -


i have dataset follow:

col1    col2        1,2,3 b        ["1","2"] c        4 

i want output as:

col1     col2 a1         1 a2         2 a3         3 b1         1 b2         2 c          4 

is possible in r? if yes, how?

try

library(splitstackshape)  csplit(transform(df1, col2= gsub('\\[|\\]|"', '', col2)), 'col2', ',', 'long')[  ,col1:= if(.n>1) paste0(col1, 1:.n) else col1, col1] #    col1 col2 #1:   a1    1 #2:   a2    2 #3:   a3    3 #4:   b1    1 #5:   b2    2 #6:    c    4 

or using base r

df2 <- stack(setnames(strsplit(gsub('[^0-9,]', '', df1$col2), ','), df1$col1))  df2$ind <-  with(df2, paste0(ind,ave(seq_along(ind), ind,      fun= function(x) if(length(x)==1) '' else seq_along(x)))) colnames(df2) <- paste0('col', 2:1) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -