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?

Viewed 28

Here is my code:

    for (x in col_names){
    time_series <- ts(df3$x, frequency=1, start = df3$index[1])
}

When I run this I get the following error:

    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")

I believe this is because R cannot read the df3$x. How do I loop through a vector and use an element of that vector as a column name of my dataframe?

1 Answers

It should be with [[

for (x in col_names){
    time_series <- ts(df3[[x]], frequency=1, start = df3$index[1])
}

assuming that col_names is vector of specific column names


In the OP's code, time_series object created will get updated in each iteration. Instead, would be better to return in a 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])
}
Related