-1

In R, I have a table formatted like this:

tab <- data.frame(col1=c('A','B','C'),
                  col2=c('after|angle|axe','boss|bike','car|cat|corn'))

  col1            col2
1    A after|angle|axe
2    B       boss|bike
3    C    car|cat|corn

I need to turn it into that:

  col1  col2
1    A after
2    A angle
3    A   axe
4    B  boss
5    B  bike
6    C   car
7    C   cat
8    C  corn

How can I do that? Is it possible without a loop and with no external libraries?

Rodrigo
  • 4,706
  • 6
  • 51
  • 94

1 Answers1

0

We can use strsplit from base R

lst1 <- strsplit(as.character(tab$col2), "|", fixed = TRUE)
data.frame(col1 = rep(tab$col1, lengths(lst1)), col2 = unlist(lst1))

With packages, it is more easier

library(tidyr)
tab %>% 
   separate_rows(col2)
akrun
  • 874,273
  • 37
  • 540
  • 662