0

In my head this seems a simple aim, but i am struggling to find a solution.

My data is laid out like this:

df <- data.frame(species = c("A", "B", "C"),
                 length= c(2, 3, 1),
                 count = c(4, 6, 1),
                 year=c(2008,2012,2008))
                
#  species length count  year
#1       A      2     4  2008
#2       B      3     6  2012
#3       C      1     1  2008

I would like to duplicate rows based on the value in count. So my data set would look like this. I dont want to drop anything other than the count column of course.

#  species length  year
#1       A      2  2008
#2       A      2  2008
#3       A      2  2008
#4       A      2  2008

I hope that makes sense.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

1 Answers1

0
library(dplyr)

df %>%
  slice(rep(1:nrow(df), times = df$count)) %>%
  select(-count)
lead-y
  • 46
  • 4