r - 使用 for 循环命名向量中的组件

标签 r vector components naming

我正在尝试将向量添加到 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/

相关文章:

C++ 无法将数据输入私有(private) vector (无效使用)

C++::vector如何保存自己的类

javascript - 子组件中的 onClick 操作发送了错误的元素

ios - 适用于 iPhone 的真实表格组件

python - 在 rpy 中传递 R 函数参数

r - 如何列出 R 包的所有演示及其来源

r - 在 data.table R 中使用 lapply .SD

generics - 收集到Vec与&Vec

angular - 根据值显示组件 - Angular 2

r - 将 R 中的每个条目的列转换为多行