[英]R: finding absolute difference with dplyr and group_by
I have the following example.我有以下示例。
I want to create a new column with the absolute difference in AGE compared to each Treat==1 in the same PairID.我想创建一个新列,其中 AGE 与同一 PairID 中的每个 Treat==1 相比具有绝对差异。
Desired output should be as shown below.所需的 output 应如下所示。
I have tried using dplyr with:我尝试使用dplyr与:
Data complete:资料齐全:
Treat <- c(1,0,0,1,0,0,1,0)
PairID <- c(1,1,1,2,2,2,3,3)
Age <- c(30,60,31,20,20,40,50,52)
D <- data.frame(Treat,PairID,Age)
D
D %>%
group_by(PairID) %>%
abs(Age - Age[Treat == 1])
in Base-R:在 Base-R 中:
D$absD <- unlist(lapply(split(D,D$PairID), function(x) abs(x$Age - x$Age[x$Treat==1])))
> D
Treat PairID Age absD
1 1 1 30 0
2 0 1 60 30
3 0 1 31 1
4 1 2 20 0
5 0 2 20 0
6 0 2 40 20
7 1 3 50 0
8 0 3 52 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.