I have time series data outputted from a lapply
and would like to cbind
them together starting from their respective start date. Here I set an example of 5 random generated time series starting from random generated dates.
set.seed(123)
d <- lapply(1:5,function(x) ts(rnorm(runif(1,5,20),0,10),start = floor(c(runif(1,2019,2020),runif(1,1,12))),frequency = 12))
I tried cbind, cbindna/cbind.na (package 'qpcR'), data.frame, cbind2, etc... I can not find the appropriate tool for this. Using a for loop filling the empty spaces seems silly. My desired output image:
CodePudding user response:
You just need cbind()
from base
. Use do.call()
because d
is a list.
d2 <- do.call(cbind, setNames(d, paste0('t', 1:length(d))))
Output
t1 t2 t3 t4 t5
Feb 2019 NA 3.598138 NA NA NA
Mar 2019 NA 4.007715 NA NA -2.416898
Apr 2019 NA 1.106827 NA NA -4.682005
May 2019 NA -5.558411 -8.185157 NA -7.729782
Jun 2019 NA 17.869131 6.849361 NA 21.499193
Jul 2019 NA 4.978505 -3.200564 NA -13.343536
Aug 2019 NA -19.666172 -13.115224 NA 4.958705
Sep 2019 NA 7.013559 -5.996083 NA 12.339762
Oct 2019 8.005543 -4.727914 -1.294107 NA 6.343621
Nov 2019 11.902066 -10.678237 8.867361 -12.6539635 4.120223
Dec 2019 -16.895557 -2.179749 -1.513960 21.6895597 7.935853
Jan 2020 12.394959 -10.260044 3.297912 12.0796200 -1.524106
Feb 2020 -1.089660 -7.288912 -32.273228 -11.2310858 -2.288958
Mar 2020 -1.172420 -6.250393 -7.717918 -4.0288484 -9.007918
Apr 2020 1.830826 -16.866933 2.865486 -4.6665535 NA
May 2020 12.805549 NA -12.205120 7.7996512 NA
Jun 2020 -17.272706 NA NA -0.8336907 NA
Jul 2020 NA NA NA 2.5331851 NA
Aug 2020 NA NA NA -0.2854676 NA
Sep 2020 NA NA NA -0.4287046 NA
Oct 2020 NA NA NA 13.6860228 NA
Nov 2020 NA NA NA -2.2577099 NA
Dec 2020 NA NA NA 15.1647060 NA
Jan 2021 NA NA NA -15.4875280 NA
Feb 2021 NA NA NA 5.8461375 NA
The output is still a ts
object.
class(d2)
# [1] "mts" "ts" "matrix"