Copy multiple columns from one data.frame file to another

Is there an easy way to get R to automatically copy columns from data.frame to another?

I have something like:

>DF1 <- data.frame(a=1:3, b=4:6)
>DF2 <- data.frame(c=-2:0, d=3:1)

and I want to get something like

>DF1
   a b  c d
1 -2 4 -2 3
2 -1 5 -1 2
3  0 6  0 1

I usually do it manually, as in

DF1$c <- DF2$c
DF1$d <- DF2$d

and this is great if I have few variables, but it becomes very time-consuming and error prone when working with multiple variables. Any idea on how to do this efficiently? This is probably pretty simple, but I swear I couldn’t find the answer for the search, thanks!

+4
source share
2 answers

The result from your example is incorrect, it should be:

> DF1$c <- DF2$c
> DF1$d <- DF2$d
> DF1
  a b  c d
1 1 4 -2 3
2 2 5 -1 2
3 3 6  0 1

Then cbinddoes the same:

> cbind(DF1, DF2)
  a b  c d
1 1 4 -2 3
2 2 5 -1 2
3 3 6  0 1
+14
source

( Jilber, , .) , -

DF1 <- cbind(DF1, DF2[!names(DF2) %in% names(DF1)])
+9

All Articles