r - 我正在循环遍历一个向量并尝试使用每个元素作为数据框列名称。如何读取 df3$x 中 $ 之后的每个元素?

标签 r time-series

这是我的代码:

    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/

相关文章:

python - 如何突出情节中的周末?

python - 将时间序列组合成具有不同时间实例的单个图

html - ShinyDashboard 中的 CSS Reactive ValueBoxes

r - 聚合/总结每组多个变量(例如总和、平均值)

r - 根据 aes 设置,facet_wrap 无法正常工作

r - 在 dplyr 中使用单个否定逻辑标准过滤多个变量

matlab - 在Matlab中生成时间戳系列?

python - 用 rpy2 修改 r 对象

r - R中同一时间序列图有多种颜色,可能吗?

r - NA 在时间序列处理中?