Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple columns to R dataframe from list

Tags:

dataframe

r

I have a dataframe:

df1

a b c
1 1 0
1 1 1
1 1 1

df2

a b c d e f
1 1 0 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
2 2 2 2 2 2

How can I add new columns to df1 from df2 that aren't in df1? to get:

df2

a b c d e f
1 1 0 0 0 0
1 1 1 0 0 0
1 1 1 0 0 0

I tried:

columns_toadd <- colnames(df1)[!(colnames(df1) %in% colnames(df2))]

for (i in 1:length(columns_toadd)){
  df$columns_toadd[[i]] <- 0
}

But this just gave:

df2

a b c columns_toadd
1 1 0 0 
1 1 1 0 
1 1 1 0 

I'd like to do this in base R as I work in an environment with limited packages.

like image 321
Chuck Avatar asked Nov 17 '25 11:11

Chuck


1 Answers

We can get the column names that are not in 'df1' using setdiff and assign those to 0

df1[setdiff(names(df2), names(df1))] <- 0
like image 172
akrun Avatar answered Nov 20 '25 03:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!