'Split data frame by decreasing number of rows in R

I have a data frame:

dates <- seq.Date(from = as.Date("2005/01/01"), to = as.Date("2022/01/01"), by = 'years')
myvar <- rnorm(n = length(dates))
mydata <- cbind.data.frame(dates, myvar)

I want to split this data from into 18 different data frames (given by the number of rows). The first data frame would contain all 18 rows, the second data frame would contain rows 2:18, the third would contain rows 3:18, and so. The final data frame would contain only the 18th row.



Solution 1:[1]

out <- lapply(rev(seq_len(nrow(mydata))), tail, x = mydata)
out[[1]]
#         dates        myvar
# 1  2005-01-01 -1.626973680
# 2  2006-01-01  0.540752205
# 3  2007-01-01 -1.513774595
# 4  2008-01-01  0.710279918
# 5  2009-01-01 -0.150721031
# 6  2010-01-01 -0.905366141
# 7  2011-01-01  0.494374069
# 8  2012-01-01 -0.489290540
# 9  2013-01-01 -0.784882029
# 10 2014-01-01 -1.046514324
# 11 2015-01-01 -0.086859898
# 12 2016-01-01 -0.001513102
# 13 2017-01-01  0.002866734
# 14 2018-01-01 -2.262867978
# 15 2019-01-01 -0.787750551
# 16 2020-01-01  0.557968261
# 17 2021-01-01  0.514520082
# 18 2022-01-01 -1.004364925
out[17:18]
# [[1]]
#         dates      myvar
# 17 2021-01-01  0.5145201
# 18 2022-01-01 -1.0043649
# [[2]]
#         dates     myvar
# 18 2022-01-01 -1.004365

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 r2evans