【问题标题】:Naming components in a vector using a for loop使用 for 循环命名向量中的组件
【发布时间】:2013-11-29 10:41:16
【问题描述】:

我正在尝试将向量添加到 for 循环中的列表中,并希望根据计数器的值来命名组件

这就是我在没有 for 循环的情况下将向量添加到列表中的方法

momentum$mom1 <- (prices[period.ends, ] / mlag(prices[period.ends,],1)-1)
momentum$mom3 <- (prices[period.ends, ] / mlag(prices[period.ends,],3)-1)
momentum$mom6 <- (prices[period.ends, ] / mlag(prices[period.ends,],6)-1)

但这看起来效率低下,必须有一种方法来创建名称“mom1”、“mom2”和“mom3”,方法是以某种方式连接“mom”和 i(作为假设值为 1 的循环中的计数器) ,3,6)。

我的想法是这样的

momentum = list()
periods <- c(1,3,6)
for (i in periods){
    momentum$paste("mom",i,sep="")<- (prices[period.ends,]/mlag(prices[period.ends,],i)-1)

}

已广泛搜索此论坛,但似乎找不到我的答案。我是 R 的初学者,非常感谢您的帮助。

【问题讨论】:

    标签: r vector components naming


    【解决方案1】:
    momentum = list()
    
    periods <- c(1,3,6)
    
    n <- length(periods)
    

    在创建列表条目后更改每个名称:

    for (i in 1:n){
      momentum[[i]] <- "stuff"
      names(momentum)[i] <- paste("mom",i,sep="")
    }
    

    现在物体动量有了所需的名称

    【讨论】:

      【解决方案2】:

      对列表的双方括号赋值将评估其参数:

      > z=list()
      > n="foo"
      > z[[n]]=99
      > z
      $foo
      [1] 99
      

      所以你不可复制的例子将是这样的:

      for (i in periods){
          momentum[[paste0("mom",i)]] <- (prices[period.ends,]/mlag(prices[period.ends,],i)-1)
      

      或者,您可以构建不带名称的列表,创建名称向量,然后使用 names(momentum) = paste0("mom",periods) 将其分配给列表

      【讨论】:

      • 非常感谢,正是我想要的。
      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 2021-12-03
      • 2021-12-01
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      相关资源
      最近更新 更多