I have a dataframe, df
, with a a number of columns of data already. I have a vector, namevector
, full of strings. I need empty columns added to df
with the names of the columns from namevector
.
I am trying to add columns with this for loop, iterating over each string in namevector
.
for (i in length(namevector)) {
df[, i] <- NA
}
but am left with this error:
Error in
[<-.data.frame
(*tmp*
, , i, value = NA) : new columns would leave holes after existing columns
Alternatively, I have thought of creating an empty dataframe with the correct names, then cbind
-ing the two dataframes together but am not sure how to go about coding this.
How would I go about resolving this?
seq_len(length(namevector))
or something similar.for (i in (seq_len(length(namevector)) + ncol(df))) ...
then change the column names.seq_len(length(...))
is a longcut toseq_along()