0

I am looking to transform a data frame df in R from:

col1   col2
X1     A;B
X2     B
X3     C;D
X4     D

into:

col1   col2
X1     A
X1     B
X2     B
X3     C
X3     D
X4     D

I have come up with a complex solution which I have misplaced, and figured there must be a simpler way to do it. Thanks for any pointers.

Mariam
  • 11
  • 2

2 Answers2

0
library(tidytext)
unnest_tokens(dat,col2,col2,to_lower=F)
    col1 col2
1     X1    A
1.1   X1    B
2     X2    B
3     X3    C
3.1   X3    D
4     X4    D

Without using packages: In base R you can do:

stack(setNames(strsplit(dat$col2,";"),dat$col1))
  values ind
1      A  X1
2      B  X1
3      B  X2
4      C  X3
5      D  X3
6      D  X4

You can arrange the columns as you want

Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

As I mentioned:

df <- read.table(text = "col1   col2
 X1     A;B
 X2     B
 X3     C;D
 X4     D",sep = "",header = TRUE)
> df
  col1 col2
1   X1  A;B
2   X2    B
3   X3  C;D
4   X4    D
> library(tidyr)
> separate_rows(df,col2,sep = ";")
  col1 col2
1   X1    A
2   X1    B
3   X2    B
4   X3    C
5   X3    D
6   X4    D
joran
  • 169,992
  • 32
  • 429
  • 468