R- add empty columns to a dataframe with specified names from a vector -
i have dataframe, df, a number of columns of data already. have vector, namevector, full of strings. need empty columns added df names of columns namevector. i trying add columns loop, iterating on each string in namevector. for (i in length(namevector)) { df[, i] <- na } but left error. error in [<-.data.frame ( *tmp* , , i, value = na) : new columns leave holes after existing columns alternatively, have thought of creating empty dataframe correct names, cbind-ing 2 dataframes not sure how go coding this. how go resolving this? the problem code in line: for(i in length(namevector)) you need ask yourself: length(namevector) ? it's 1 number. you're saying: for(i in 11) df[,i] <- na or more simply: df[,11] <- na that's why you're getting error. want is: for(i in namevector) df[,i] <- na or more simply: df[,namevector] <- na