这是我的代码:
for (x in col_names){
time_series <- ts(df3$x, frequency=1, start = df3$index[1])
}
当我运行此程序时,出现以下错误:
Error in ts(df3$x, frequency = 1, start = df3$index[1]): 'ts' object must have one or more observations
Traceback:
1. ts(df3$x, frequency = 1, start = df3$index[1])
2. stop("'ts' object must have one or more observations")
我相信这是因为 R 无法读取 df3$x
。如何循环遍历向量并使用该向量的元素作为数据帧的列名称?
最佳答案
应该与[[
for (x in col_names){
time_series <- ts(df3[[x]], frequency=1, start = df3$index[1])
}
假设col_names
是特定列名称的向量
在OP的代码中,创建的time_series
对象将在每次迭代中更新。相反,最好返回 list
time_series_list <- vector('list' length(col_names))
names(time_series_list) <- col_names
for (x in col_names){
time_series_list[[x]] <- ts(df3[[x]], frequency=1, start = df3$index[1])
}
关于r - 我正在循环遍历一个向量并尝试使用每个元素作为数据框列名称。如何读取 df3$x 中 $ 之后的每个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68946745/