Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying multiple columns from one data.frame to another

Tags:

dataframe

r

Is there a simple way to make R automatically copy columns from a 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'd normally do it by hand, as in

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

and that's fine as long as I have few variables, but it becomes very time consuming and prone to error when dealing with several variables. Any idea on how to do this efficiently? It's probably quite simple but I swear I wasn't able to find an answer googling, thank you!

like image 987
lambda_vu Avatar asked Oct 05 '13 18:10

lambda_vu


2 Answers

The result from your example is not correct, 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 cbind does exactly the same:

> cbind(DF1, DF2)
  a b  c d
1 1 4 -2 3
2 2 5 -1 2
3 3 6  0 1
like image 195
Jilber Urbina Avatar answered Oct 19 '22 14:10

Jilber Urbina


(I was going to add this as a comment to Jilber's now deleted and then undeleted post.) Might be safer to recommend something like

DF1 <- cbind(DF1, DF2[!names(DF2) %in% names(DF1)])
like image 31
IRTFM Avatar answered Oct 19 '22 16:10

IRTFM