我正在遍历一个向量并尝试将每个元素用作数据框列名。如何在 df3$x 中的 $ 之后读取每个元素?
I'm looping through a vector and trying to use each element as a dataframe column name. How do I get each element to be read after the $ in df3$x?
这是我的代码:
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
中 return 会更好
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])
}
这是我的代码:
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])
}