3

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.

6
  • 3
    Try df1[setdiff(names(df2), names(df1))] <- 0 Commented Dec 14, 2017 at 13:25
  • What is definition of new column? Is it column name or content? Also, number of rows differ. Commented Dec 14, 2017 at 13:26
  • @akrun I just want the names of the columns in df2 not in df1 added onto df1 with a 0 in each row. I'm not focussed on the length atm. Commented Dec 14, 2017 at 13:27
  • 1
    @Chuck akrun's code will give you exactly that Commented Dec 14, 2017 at 13:27
  • 1
    @akrun. Worked perfectly. Thanks a lot. Happy to accept if answer. Commented Dec 14, 2017 at 13:29

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.