【问题标题】:extra list element is created while creating list of xts in a loop in R在 R 的循环中创建 xts 列表时会创建额外的列表元素
【发布时间】:2019-04-28 01:16:38
【问题描述】:

我正在尝试使用循环创建 xts 对象列表:

x <- list()#creating list of xts
#n is number of columns, n is 13
for(i in 1:n-1)
{
  x[[(paste0("cor_BG_", i))]]<-as.xts(dcccor[1,i+1,])
  }
#binding all correlation pairs together
combined.xts <- do.call("merge.xts", x)

最后一行合并了所有 xts 文件,例如 cor_BG_0,cor_BG_1,cor_BG_3.....直到 cor_BG_12。问题是我的循环应该生成带有第一个元素 cor_BG_1 的 xts 文件,因为 n 应该是 1 根据第一次迭代的循环。但是,它正在生成 xts cor_BG_0 而不在循环中传递 n=0 。我无法理解这个额外的 xts 是如何生成的,以及如何摆脱它。

【问题讨论】:

    标签: r list loops merge xts


    【解决方案1】:

    1:n-1 返回 (1-1):(n-1) - 这就是 0 的来源。

    你需要的是1:(n-1)

    【讨论】:

    • 亲爱的@Milan Valášek 非常感谢您的帮助。这是工作。但是为什么代码本身会这样做(1-1)?任何想法将不胜感激。
    • 不客气!这就是 x:y - 1 语法的评估方式。您的意思是 x:(y - 1),但 R 将其读作 (x:y) - 1
    • @gauravkumar:我强烈建议您养成使用seq()seq_len()seq_along() 等在for 循环中创建迭代器的习惯。当n = 0 时,它们在边缘情况下表现正确,其中1:(n-1) 模式将迭代i = c(1, 0, -1)
    猜你喜欢
    • 1970-01-01
    • 2013-07-23
    • 2019-06-19
    • 2020-11-14
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多