Gao Lin
Gao Lin

Reputation: 21

In R, how do I select all variables from one data frame that are in another data frame?

I have two data frames a and b (with more variables). Now I would like to keep all the variables from b and combine a and b together. How should I do? Will appreciate any wise solutions.

Upvotes: 0

Views: 890

Answers (1)

harrison
harrison

Reputation: 26

Let's say you only want to keep the first two variables in a.
b contains additional information about the first two variables in a.
Code below may help:

a <- data.frame("Var1" = 1:5, "Var2" = 1:5, "Var3" = 1:5)
b <- data.frame("Var1" = 6:10, "Var2" = 6:10, "Col3" = 6:10, "Col4" = 6:10)

b <- b[, which(names(b) %in% names(a))]
a <- a[,1:2]

c <- rbind(a,b)

Upvotes: 1

Related Questions