S31
S31

Reputation: 934

Subtract two dataframes for only matching columns

Quick question,

if I have two dataframes with overlapping columns that don't match in order, such as:

df1
Chocolate    Strawberry
2            15
3            10
4            5

df2
Strawberry   Chocolate     Vanilla
14           4             30
9            4             15.2
5            4             10

And I wanted to subtract the two dataframes for only the matching columns and ignore any columns that aren't overlapping.

Desired result:

Chocolate     Strawberry
-2            1
-1            1
 0            0

Sample Code:

df1 <- data.frame(chocolate = c(2,3,4), strawberry = c(15,10,5))
df2 <- data.frame(strawberry = c(14,9,5), chocolate = c(4,4,4), vanilla = c(30,15.2,10))

Upvotes: 4

Views: 1566

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

We can use intersect to get the common columns and then sort them so that the columns are in same order while subtracting irrespective of their order in their respective data frames (df1 and df2).

cols <- sort(intersect(names(df1), names(df2)))
df1[cols] - df2[cols]

#  chocolate strawberry
#1        -2          1
#2        -1          1
#3         0          0

Upvotes: 6

Related Questions