2

Suppose I have this data frame:

df <- data.frame(ids=c('1,2','3,4'), vals=c('a', 'b'))

and I want to end up with this one:

data.frame(ids=c('1', '2', '3', '4'), vals=c('a', 'a', 'b', 'b'))

In words: one separate row for each value in the comma-separated lists in ids, with the associated vals duplicated.

I'd like to use the tidyverse. I'm pretty sure I should use pivot_longer, maybe with names_sep, but after reading and fiddling it's not obvious to me.

Help?

dfrankow
  • 20,191
  • 41
  • 152
  • 214

1 Answers1

3

We can use separate_rows instead of pivot_longer

library(tidyr)
df %>% 
   separate_rows(ids)
# A tibble: 4 x 2
#  ids   vals 
#  <chr> <chr>
#1 1     a    
#2 2     a    
#3 3     b    
#4 4     b    
akrun
  • 874,273
  • 37
  • 540
  • 662