从一个数据框中减去另一个数据 [英] 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
我想根据它们的位置从数据帧B中的值中减去数据帧B中的值。因此,例如:
对于DVH1,VU将为7-2(或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
推荐答案
使用此:
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")]
编辑:奖励:如果成对的列太多(不仅是VU,U和P),您可以使用:
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
这篇关于从一个数据框中减去另一个数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文