Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unlist and split a column without losing information of other column in R

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading