我正在尝试将向量添加到 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)
但这看起来效率很低,并且必须有一种方法可以通过某种方式连接“mom”和 i(假设值为 1 的循环中的计数器)来创建名称“mom1”、“mom2”和“mom3” ,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 初学者,非常感谢您的帮助。
最佳答案
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="")
}
现在物体动量有了所需的名称
关于r - 使用 for 循环命名向量中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20283822/