do.call(rbind) 上的 R 设置列名称

R setting column name on do.call(rbind)

总而言之,我希望将累积量列添加到 XTS 对象。但是,在调用 do.call(rbind... 时,我发现原来的 XTS 被覆盖了。

# Reproducible example data
foo <- rnorm(5)
bar <- seq(as.Date("1970-01-01"), length = 5, by = "days")
foobar <- xts(x = foo, order.by = bar)
names(foobar)[1] <- "Volume"
# My processing ...
foobar_months <- split(foobar[,"Volume"],f="months")
foobar_vol_mtd <- lapply(foobar_months,FUN=cumsum)
# This is what is not working for me because Volume overwrites original Volume
foobar <- do.call(rbind,foobar_vol_mtd) 

函数do.call(rbind, list) 将对所有列表元素进行rbind。您没有将该列表附加到原始列表。你可以做的是:

foobar2 <- do.call(rbind,foobar_vol_mtd)
foobar <- rbind(foobar, foobar2)

将该列表中的所有元素绑定在一起,然后将结果绑定到原始列表。

结果:

               Volume
1970-01-01  0.8995890
1970-01-01  0.8995890
1970-01-02 -0.5057975
1970-01-02  0.3937916
1970-01-03 -0.1861275
1970-01-03  0.2076641
1970-01-04 -1.1641303
1970-01-04 -0.9564663
1970-01-05  0.3157536
1970-01-05 -0.6407127

结果会因 rnorm(5) 和未设置种子而有所不同。

附加为新列

如我所说,rbind 追加新行并且所有列应该相同。如果您想作为新列追加,请尝试:

foobar2 <- do.call(rbind,foobar_vol_mtd)
foobar3 = merge(foobar, foobar2)

我对这种情况的结果是(新的随机值,所以不要与上面的比较):

                Volume  Volume.1
1970-01-01  1.96291153 1.9629115
1970-01-02 -0.41771710 1.5451944
1970-01-03 -0.08827657 1.4569179
1970-01-04 -0.57243569 0.8844822
1970-01-05 -0.06093953 0.8235426

然后将列名称更改为names(foobar)[2] = "new_name"

您也可以在合并前重命名:

foobar2 <- do.call(rbind,foobar_vol_mtd)
names(foobar2) = 'newname'
foobar3 = merge(foobar, foobar2)

并且合并将像以前一样按时间索引完成。