sushant mehrotra
sushant mehrotra

Reputation: 63

dropping uncommon columns from 2 dataframes in r

this is my first time posting and i am new to R, so please help me out :)

Question

I have 2 data frames. There are some columns present in both data frames but some columns are present in only 1 data frame. I wish to identify and retain the columns present in both data frames and drop the columns present in any 1 data frame. How can I do this?

> df1 <- data.frame(a=c(1,2,3,4,5),b=c(2,4,6,8,10),c=c(3,6,9,12,15),x=c(4,8,12,16,20),y=c(5,10,15,20,25))
> df2 <- data.frame(b=c(1,5,10),c=c(2,6,11),y=c(3,7,12),z=c(4,8,13))
> view(df1)
  a   b   c   x   y
  1   2   3   4   5
  2   4   6   8  10
  3   6   9  12  15
  4   8  12  16  20
  5  10  15  20  25
> view(df2)
  b   c   y   z
  1   2   3   4
  5   6   7   8
 10  11  12  13

Desired Output:

> view(df1)
  b   c   y
  2   3   5
  4   6  10
  6   9  15
  8  12  20
 10  15  25
> view(df2)
  b   c   y
  1   2   3
  5   6   7
 10  11  12

Upvotes: 2

Views: 188

Answers (1)

akrun
akrun

Reputation: 887028

We can use intersect to get the column names that are common in both datasets. Subset the dataset using this index.

nm1 <- intersect(names(df1), names(df2))
df1[nm1]
df2[nm2]

Upvotes: 4

Related Questions