How to transform/simplify a data.frame with timeseries in columns to an "indexed" shorter version?

79 Views Asked by At

How do I go from image #1 to #2 in R ?

I would expect this transformation to be so common in timeseries analysis that xts::, zoo:: or data.table:: would have a pre-built routine to make the series "indexed" (note the Index in red in the second image) automagically with a one-liner.

I can manually do this looping/apply-ing over the columns but want to learn if there is a pre-baked solution to this (expectedly very common) dataframe transformation.

This question is somewhat similar. The upvoted solution uses a rather intricate

do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))) 

that I would like to avoid.

Image #1:

Image 1:

Image #2:

Image 2:

Image 1

sample data.frame as requested:

df <- data.frame(Date = seq(from=as.Date("2010-01-01"), to=as.Date("2010-02-15"), by=1),
                 `2008/09` = c(rnorm(10), rep(NA,36)),
                 `2009/10` = c(rep(NA, 3),  rnorm(10), rep(NA, 33)),
                 `2010/11` = c(rep(NA, 5),  rnorm(10), rep(NA, 31)),
                 `2011/12` = c(rep(NA, 10), rnorm(11), rep(NA, 25))
                 )
0

There are 0 best solutions below