Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

r - Subtract values in one dataframe from another

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...