2

I'm trying to split a column by a delimeter, comma in this case, and then make duplicate rows based on the number of elements between commas. I've used str_split_fixed() which will split the column appropriately, but I don't know how to use that to make duplicate rows.

As an example, I have this dataframe:

V1  V2 V3 V4
foo a  b  1,2,3  
bar c  d  1,2

And would like to get it to this dataframe as output:

V1  V2 V3 V4
foo a  b  1
foo a  b  2
foo a  b  3
bar c  d  1
bar c  d  2
bactro
  • 79
  • 6

1 Answers1

-1

For this purpose, there is separate_rows

library(tidyverse)
df1 %>%
     separate_rows(V4, sep=",", convert = TRUE)
#.  V1 V2 V3 V4
#1 foo  a  b  1
#2 foo  a  b  2
#3 foo  a  b  3
#4 bar  c  d  1
#5 bar  c  d  2

data

df1 <- structure(list(V1 = c("foo", "bar"), V2 = c("a", "c"), V3 = c("b", 
"d"), V4 = c("1,2,3", "1,2")), class = "data.frame", row.names = c(NA, 
-2L))
akrun
  • 874,273
  • 37
  • 540
  • 662