我有一个 xts 对象列表
set.seed(1)
library(xts)
tm <- Sys.time()+1:10
f <- function(){
m <- matrix(1:40,ncol = 4, dimnames = list(NULL, paste0("x",1:4)))
xts(m ,tm)[-sample(10,sample(9,1))]
}
li <- lapply(1:3,\(x) f())
names(li) <- paste0("Obj ", 1:length(li))
li
$`Obj 1`
x1 x2 x3 x4
2024-03-06 18:26:05 6 16 26 36
$`Obj 2`
x1 x2 x3 x4
2024-03-06 18:26:01 2 12 22 32
2024-03-06 18:26:02 3 13 23 33
2024-03-06 18:26:03 4 14 24 34
2024-03-06 18:26:05 6 16 26 36
2024-03-06 18:26:06 7 17 27 37
2024-03-06 18:26:07 8 18 28 38
2024-03-06 18:26:09 10 20 30 40
$`Obj 3`
x1 x2 x3 x4
2024-03-06 18:26:01 2 12 22 32
2024-03-06 18:26:02 3 13 23 33
2024-03-06 18:26:03 4 14 24 34
2024-03-06 18:26:07 8 18 28 38
我需要使用
merge
对齐这些列表对象并将它们返回到列表。
merge_li <- do.call(merge, li)
x1 x2 x3 x4 x1.1 x2.1 x3.1 x4.1 x1.2 x2.2 x3.2 x4.2
2024-03-06 18:26:01 NA NA NA NA 2 12 22 32 2 12 22 32
2024-03-06 18:26:02 NA NA NA NA 3 13 23 33 3 13 23 33
2024-03-06 18:26:03 NA NA NA NA 4 14 24 34 4 14 24 34
2024-03-06 18:26:05 6 16 26 36 6 16 26 36 NA NA NA NA
2024-03-06 18:26:06 NA NA NA NA 7 17 27 37 NA NA NA NA
2024-03-06 18:26:07 NA NA NA NA 8 18 28 38 8 18 28 38
2024-03-06 18:26:09 NA NA NA NA 10 20 30 40 NA NA NA NA
现在如何将
merge_li
返回到li
(列表)形式?
并保存 li
的名称,最好是里面的列
id_xts <- li |> lapply(index) |> do.call(what = c) |> unique() |> sort() |> as.xts()
lapply(li, merge, id_xts, all = TRUE)
$`Obj 1`
x1 x2 x3 x4
2024-03-07 22:00:34 NA NA NA NA
2024-03-07 22:00:35 NA NA NA NA
2024-03-07 22:00:36 NA NA NA NA
2024-03-07 22:00:38 6 16 26 36
2024-03-07 22:00:39 NA NA NA NA
2024-03-07 22:00:40 NA NA NA NA
2024-03-07 22:00:42 NA NA NA NA
$`Obj 2`
x1 x2 x3 x4
2024-03-07 22:00:34 2 12 22 32
2024-03-07 22:00:35 3 13 23 33
2024-03-07 22:00:36 4 14 24 34
2024-03-07 22:00:38 6 16 26 36
2024-03-07 22:00:39 7 17 27 37
2024-03-07 22:00:40 8 18 28 38
2024-03-07 22:00:42 10 20 30 40
$`Obj 3`
x1 x2 x3 x4
2024-03-07 22:00:34 2 12 22 32
2024-03-07 22:00:35 3 13 23 33
2024-03-07 22:00:36 4 14 24 34
2024-03-07 22:00:38 NA NA NA NA
2024-03-07 22:00:39 NA NA NA NA
2024-03-07 22:00:40 8 18 28 38
2024-03-07 22:00:42 NA NA NA NA