How to separate Column string by ; and assign row value in R

Viewed 25

I have an example dataframe

df = data.frame(day = c("Monday", "Tuesday; Wednesday", "Thursday"),
                      c(2, 3, 5))

I want to separate all strings with "; " and assign the value of the second column like this:

      df_goal = data.frame(value= c("Monday", "Tuesday", "Wednesday", "Thursday"),
                           c(2, 3, 3, 5))

My original data is much larger so I am looking for larger scale applicable solution

1 Answers

Use separate_rows, by default, the default separator is punctuation signs; but you can manually indicate it using sep = "; "

library(tidyr)
separate_rows(df, day)
#separate_rows(df, day, sep = "; ")

output

  day       c.2..3..5.
  <chr>          <dbl>
1 Monday             2
2 Tuesday            3
3 Wednesday          3
4 Thursday           5
Related