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

Separate dataframe into more rows by comma in column?

Sorry if the title is confusing, but hopefully this example is clear.

I have a dataframe like this:

> dput(dt1)
structure(list(Variable = c("Apple", "Orange"), Value = c("12, 5", 
"15")), class = "data.frame", row.names = c(NA, -2L))

As you can see, the Value column contains a comma in the first row. I would like to separate this, so that the final dataframe looks like this:

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

> dput(dt2)
structure(list(Variable = c("Apple", "Apple", "Orange"), Value = c(12L, 
5L, 15L)), class = "data.frame", row.names = c(NA, -3L))

All other columns should duplicate any time we are separating the comma.

>Solution :

You can use tidyr::separate_rows()

dt1 <- structure(list(Variable = c("Apple", "Orange"), Value = c("12, 5", 
                                                          "15")), class = "data.frame", row.names = c(NA, -2L))


tidyr::separate_rows(dt1, Value)
#> # A tibble: 3 x 2
#>   Variable Value
#>   <chr>    <chr>
#> 1 Apple    12   
#> 2 Apple    5    
#> 3 Orange   15

Created on 2023-07-18 by the reprex package (v2.0.0)

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