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.
Asked
Active
Viewed 408 times
0
-
3Please provide an example of two data frames and the output you want. Many things aren't 100% clear with only a text description e.g. does "combine" mean a `cbind` or `rbind`-like operation? See [/how-to-make-a-great-r-reproducible-example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – IceCreamToucan Nov 15 '19 at 15:48
-
`only_a <- setdiff(names(a), names(b))` then `cbind(b, a[only_a])`. This only works if `a` and `b` have the same number of rows. – Rui Barradas Nov 15 '19 at 15:50
-
1The OP says she *"would like to keep all the variables from b"* and combine the df's. I understand this as to keep `b` and the columns in `a` that are *not in `b`*. – Rui Barradas Nov 15 '19 at 15:53
1 Answers
1
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)