1

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]
lmo
  • 37,904
  • 9
  • 56
  • 69
Nic
  • 1,262
  • 2
  • 22
  • 42

1 Answers1

3

We can use intersect to get the common names from two dataframes

intersect(names(obj1), names(obj2))

Now to select these common columns into a new dataframe obj3 we can do

obj3 <- obj1[, intersect(names(obj1), names(obj2))]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • can you please modify the answer as to adapt it after my latest modification?: obj3 <- obj1[, intersect(names(obj1), names(obj2))] – Nic Dec 08 '16 at 11:37