Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract two dataframes for only matching columns

Tags:

r

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))
like image 428
S31 Avatar asked Oct 25 '25 01:10

S31


1 Answers

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
like image 131
Ronak Shah Avatar answered Oct 27 '25 14:10

Ronak Shah