Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add empty columns to a dataframe with specified names from a vector

Tags:

dataframe

r

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?

like image 596
user2631296 Avatar asked Aug 13 '13 16:08

user2631296


People also ask

How do you add an empty column to a specific position in pandas?

Use DataFrame. insert() method to add an empty column at any position on the pandas DataFrame. This adds a column inplace on the existing DataFrame object.

How do I add an empty column to a DataFrame in R?

The easiest way to add an empty column to a dataframe in R is to use the add_column() method: dataf %>% add_column(new_col = NA) .

How do I create a new DataFrame with column names in R?

How to Create a Data Frame. We can create a dataframe in R by passing the variable a,b,c,d into the data. frame() function. We can R create dataframe and name the columns with name() and simply specify the name of the variables.


2 Answers

The problem with your code is in the line:

for(i in length(namevector)) 

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11) df[,i] <- NA 

Or more simply:

df[,11] <- NA 

That's why you're getting an error. What you want is:

for(i in namevector)     df[,i] <- NA 

Or more simply:

df[,namevector] <- NA 
like image 131
Señor O Avatar answered Oct 21 '22 11:10

Señor O


set.seed(1) example <- data.frame(col1 = rnorm(10, 0, 1), col2 = rnorm(10, 2, 3)) namevector <- c("col3", "col4") example[ , namevector] <- NA  example #          col1       col2 col3 col4 # 1  -0.6264538  6.5353435   NA   NA # 2   0.1836433  3.1695297   NA   NA # 3  -0.8356286  0.1362783   NA   NA # 4   1.5952808 -4.6440997   NA   NA # 5   0.3295078  5.3747928   NA   NA # 6  -0.8204684  1.8651992   NA   NA # 7   0.4874291  1.9514292   NA   NA # 8   0.7383247  4.8315086   NA   NA # 9   0.5757814  4.4636636   NA   NA # 10 -0.3053884  3.7817040   NA   NA 
like image 44
dayne Avatar answered Oct 21 '22 09:10

dayne