1

Suppose I have a dataframe like this one:

library(tibble)

df <- tribble (
  ~ day, ~ event,
      1,       3,
      2,       1,
      3,       4)

And I want to obtain this:

output <- tribble(
  ~ day,
      1,
      1,
      1,
      2,
      3,
      3,
      3,
      3)

We could do this in base R:

output <- data.frame(day = rep(df$day, df$event))

But is there a tidyverse way to do it?

pietrodito
  • 1,783
  • 15
  • 24

1 Answers1

1

We can use uncount

library(dplyr)
library(tidyr)
df %>%
   uncount(event)

-output

# A tibble: 8 x 1
#    day
#  <dbl>
#1     1
#2     1
#3     1
#4     2
#5     3
#6     3
#7     3
#8     3
akrun
  • 874,273
  • 37
  • 540
  • 662