How to "expand/explode" a data.frame variable

Hi,

I would like to "expand" a rather complex data frame by splitting the content of one variable by "|" symbol. To illustrate this problem, I have created an example using the simpler foo data frame. I could use base R to split the content of V2 and V4 and form a new data.frame but it feels like there should be a more elegant solution using tidyverse. Any insight would be welcome.

require(tidyverse)
foo <- data.frame(
  V1 = 1,
  V2 = 'A|B|C',
  V3 = 2,
  V4 = 'X|Y|Z'
)
# Not working
foo %>% mutate(
  V2 = unlist(strsplit(V2, split = "[|]")),
  V4 = unlist(strsplit(V4, split = "[|]"))
)

# Intended result
bar <- data.frame(
  V1 = c(1, 1, 1),
  V2 = c('A', 'B', 'C'),
  V3 = c(2, 2, 2),
  V4 = c('X', 'Y', 'Z')
)
bar2 <- separate_rows(foo,V2,V4)
1 Like

Great!
Thanks @nirgrahamuk

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.