drysci
drysci

Reputation: 13

R to separate rows for multiple columns linking ordered values

Is there a way to use separate_rows from tidyverse or equivalent over multiple columns where the values between columns will be matched based on the order they appeared? E.g. convert

d <- data.frame(a=c(1:3), 
       b=c("name1, name2, name3", "name4", "name5, name6"),
       c=c("match1, match2, match3", "match4", "match5, match6"))

into

a b c
1 name1 match1
2 name2 match2
3 name3 match3
4 name4 match4
5 name5 match5
6 name6 match6

Thanks

Upvotes: 0

Views: 247

Answers (1)

akrun
akrun

Reputation: 887088

We may use separate_rows on multiple columns if they have the same number of string separators

library(tidyr)
library(dplyr)
d %>%
   separate_rows(b, c)

-output

# A tibble: 6 × 3
      a b     c     
  <int> <chr> <chr> 
1     1 name1 match1
2     1 name2 match2
3     1 name3 match3
4     2 name4 match4
5     3 name5 match5
6     3 name6 match6

Upvotes: 0

Related Questions