Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract values in one dataframe from another

Tags:

dataframe

r

I have two data frames: (these are shortened versions of them)

A

    Link    VU  U   P
1   DVH1    7   1   37
2   DVH2    7   0   38
3   DVH3    10  1   35

B

    Link    VU  U   P
1   DVH1    2   0   15
2   DVH2    4   0   14
3   DVH3    0   0   5

I want to substract the values in data frame B from those in A based on their location. So for example: For DVH1, VU would be 7-2 (or 5), and the resulting data frame would look like:

    Link    VU  U   P
1   DVH1    5   1   22
2   DVH2    3   0   24
3   DVH3    10  1   30
like image 308
EricaO Avatar asked Sep 09 '13 23:09

EricaO


People also ask

How do you subtract values in pandas?

Pandas DataFrame sub() MethodThe sub() method subtracts each value in the DataFrame with a specified value. The specified value must be an object that can be subtracted from the values in the DataFrame.

How do you subtract two sets of data?

Accepted Answer In order to subtract two data sets with different resolutions, it is required to convert the resolution of one of the data sets to match that of the other one. Use MATLAB function GRIDDATA for this purpose. ZZ3 = griddata(XX,YY,ZZ,XX2,YY2);

How do you find the difference between two DataFrames in pandas?

The compare method in pandas shows the differences between two DataFrames. It compares two data frames, row-wise and column-wise, and presents the differences side by side. The compare method can only compare DataFrames of the same shape, with exact dimensions and identical row and column labels.


1 Answers

Use this:

within(merge(A,B,by="Link"), {
    VU <- VU.x - VU.y
    U <- U.x - U.y
    P <- P.x - P.y
})[,c("Link","VU","U","P")]

EDIT: Bonus: if there are too many paired columns (not just VU, U and P) you can use this:

M <- merge(A,B,by="Link")

S <- M[,grepl("*\\.x$",names(M))] - M[,grepl("*\\.y$",names(M))]

cbind(M[,1,drop=FALSE],S)

#  Link VU.x U.x P.x
#1 DVH1    5   1  22
#2 DVH2    3   0  24
#3 DVH3   10   1  30
like image 145
Ferdinand.kraft Avatar answered Oct 02 '22 19:10

Ferdinand.kraft