将多个列从一个数据框复制到另一个数据框(Copying multiple columns from one data.frame to another)

有没有一种简单的方法可以让R自动将data.frame中的列复制到另一个?

我有这样的东西:

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

我想得到类似的东西

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

我通常会手工做,如在

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

只要我有几个变量,这很好,但是当处理几个变量时,它变得非常耗时并且容易出错。 任何想法如何有效地做到这一点? 这可能很简单,但我发誓我无法找到答案谷歌搜索,谢谢!

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!

最满意答案

您示例的结果不正确,应该是:

> 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

然后cbind完全一样:

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

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将多个列从一个数据框复制到另一个数据框(Copying multiple columns from one data.frame to another)

有没有一种简单的方法可以让R自动将data.frame中的列复制到另一个?

我有这样的东西:

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

我想得到类似的东西

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

我通常会手工做,如在

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

只要我有几个变量,这很好,但是当处理几个变量时,它变得非常耗时并且容易出错。 任何想法如何有效地做到这一点? 这可能很简单,但我发誓我无法找到答案谷歌搜索,谢谢!

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!

最满意答案

您示例的结果不正确,应该是:

> 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

然后cbind完全一样:

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

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