I need to split data.frame
by some variable and calculate difference between each row's value and value from some other specified row.
In example below, I split df
by v1
. Then for each row of v3
calculate difference between the actual value and v3[v2 == "C"]
.
v1 <- rep(1:4,each = 3)
v2 <- rep(c("A","B","C"),4)
v3 <- rep(1:5,3)[1:12]
res <- c(-2,-1,0,3,4,0,-2,-1,0,3,-1,0)
df <- data.frame(v1,v2,v3,res)
df
v1 v2 v3 res
1 1 A 1 -2
2 1 B 2 -1
3 1 C 3 0
4 2 A 4 3
5 2 B 5 4
6 2 C 1 0
7 3 A 2 -2
8 3 B 3 -1
9 3 C 4 0
10 4 A 5 3
11 4 B 1 -1
12 4 C 2 0
I prefer plyr
or data.table
, if possible.
Here is a data table solution:
library(data.table)
setDT(df)
df[, new := v3 - v3[v2=="C"], by = "v1"]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments