I have a column with special character ";" that I want to separate into new rows without loosing information of other columns.
let’s say, this is my df:
col1 year
A;B 2010
A 2010
B 2011
B;C 2012
the desired result:
col1 year
A 2010
B 2010
A 2010
B 2011
B 2012
C 2012
I know how to seperate col1 using strsplit :
unlist(strsplit(df[,1], ";")
but this does not keep the information of other columns.
>Solution :
We can use separate_rows
library(tidyr)
separate_rows(df, col1, sep = ";")
If we want to use strsplit, then have to replicate the rows based on the length of list elements (lengths)
lst1 <- strsplit(df$col1, ";")
df1 <- df[rep(seq_len(nrow(df)), lengths(lst1)),]
df1$col1 <- unlist(lst1)