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 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -