I have an object obj1
containing columns A, B, C, D, xx, yy
. Another object obj2
contains columns B
and C
. I want to retrieve all columns which are present in both obj1
and obj2
and stock them in obj3.
Doing this name by name works:
col_names <- names(obj2) % this returns strings "B", "C"
for(i in 1:length(col_names)){
matching_col <- obj1[, match(x = col_names[i], names(obj1))]
}
Is there a way of doing this without the for loop, something like:
matching_cols <- obj1[, match(x = names(obj2), names(obj1))]
The result would be something like:
obj3 <- obj1[, matching_cols]