ccwiris
ccwiris

Reputation: 29

Splitting strings in multiple columns into multiple rows in R

df <- data.frame(Column1=c("1", "2", "3"), 
  Column2=c("craft1-craft2-craft3", "craft4-craft5", "craft6-craft7"), 
  Column3=c("order1,order2,order3", "order4,order5", "order6,order7"))

The df looks like this:

Column1      Column2                     Column3
1            craft1-craft2-craft3        order1,order2,order3
2            craft4-craft5               order4,order5,order6
3            craft6-craft7               order6,order7

The table I want in the end:

Column1      Column2                     Column3
1            craft1                      order1
1            craft2                      order2
1            craft3                      order3
2            craft4                      order4
2            craft5                      order5
3            craft6                      order6
3            craft7                      order7

bascially, I want each one in column2 corresponding to each one in column3. separate_rows() function is not working, it will give me craft1 order1, craft1 order2, craft1 order3, etc.

Anyone know how to do that?

Upvotes: 0

Views: 36

Answers (1)

akrun
akrun

Reputation: 887741

Use separate_rows with multiple delimiters in sep

library(dplyr)
library(tidyr)
df %>% 
   separate_rows(c(Column2, Column3), sep = "[-,]")

-output

# A tibble: 7 × 3
  Column1 Column2 Column3
  <chr>   <chr>   <chr>  
1 1       craft1  order1 
2 1       craft2  order2 
3 1       craft3  order3 
4 2       craft4  order4 
5 2       craft5  order5 
6 3       craft6  order6 
7 3       craft7  order7 

Upvotes: 2

Related Questions