繁体   English   中英

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

[英]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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM