I am trying to repeat rows in R multiple times (how often is determined by a column). My initial code works only sometimes for some reason.
start <- c(1901, 1902, 1950, 1980, 1980)
end <- c(1905, 1910, 1951, 1999, 1985)
df <- data.frame(start, end)
df$count <- df$end - df$start
I am trying to repeat the rows as many times as the difference between start and end. Each year gets one row (the +1 is necessary, so the start and end year both have a row as well).
The code snippet in question which is working only sometimes is the following:
df<- df[rep(rownames(df), df$count +1), ]
It sometimes says the "times" argument is invalid.
I think you want
df[rep(seq_along(df$count), df$count), ]
This replicates the sequence 1:length(df$count)
with each of df$count
times.