This is basically a sensitivity experiment for three id
groups. Each group has 4 rows. The first group (batch1
) has fixed dx
and varied dy
. The 2nd group (batch1
) and 3rd group (batch2
) have varied dx
and fixed dy
.
I want to calculate the differences between the row id
ended in 1
and the other rows ended in 2
, 3
, and 4
for each group.
How do I go about doing this? I'm open to any dplyr
or data.table
solutions. Thanks!
library(data.table)
dt <- data.table(
id = as.factor(c("batch1_dx0.0_dy-2.1_4", "batch1_dx0.0_dy0.155_3",
"batch1_dx0.0_dy1.23_2", "batch1_dx0.0_dy1_1",
"batch1_dx-0.8_dy1.0_2", "batch1_dx0_dy1.0_1",
"batch1_dx1.321_dy1.0_3", "batch1_dx4.12_dy1.0_4",
"batch2_dx-0.8_dy1.0_2", "batch2_dx0_dy1.0_1",
"batch2_dx1.321_dy1.0_3", "batch2_dx4.12_dy1.0_4")),
val1 = c(6, 2, 2, 0, 3, 1, 3, 3, 4, 5, 1),
val2 = c(6, 4, 2, 1, 1, 1, 5, 3, 2, 8, 9),
val3 = c(6, 3, 3, 0, 4, 2, 4, 1, 5, 7, 1))
id val1 val2 val3
1: batch1_dx0.0_dy-2.1_4 6 6 6
2: batch1_dx0.0_dy0.155_3 2 4 3
3: batch1_dx0.0_dy1.23_2 2 2 3
4: batch1_dx0.0_dy1_1 0 1 0
5: batch1_dx-0.8_dy1.0_2 3 1 4
6: batch1_dx0_dy1.0_1 1 1 2
7: batch1_dx1.321_dy1.0_3 3 5 4
8: batch1_dx4.12_dy1.0_4 3 3 1
9: batch2_dx-0.8_dy1.0_2 4 2 5
10: batch2_dx0_dy1.0_1 5 8 7
11: batch2_dx1.321_dy1.0_3 1 9 1
12: batch2_dx4.12_dy1.0_4 6 6 6
Expected output
id val1 val2 val3 dval1 dval2 dval3
batch1_dx0.0_dy-2.1_4 6 6 6 6 5 6
batch1_dx0.0_dy0.155_3 2 4 3 2 3 3
batch1_dx0.0_dy1.23_2 2 2 3 2 1 3
batch1_dx0.0_dy1_1 0 1 0 0 0 0
batch1_dx-0.8_dy1.0_2 3 1 4 2 0 2
batch1_dx0_dy1.0_1 1 1 2 0 0 0
batch1_dx1.321_dy1.0_3 3 5 4 2 4 2
batch1_dx4.12_dy1.0_4 3 3 1 2 2 -1
batch2_dx-0.8_dy1.0_2 4 2 5 -1 -6 -2
batch2_dx0_dy1.0_1 5 8 7 0 0 0
batch2_dx1.321_dy1.0_3 1 9 1 -4 1 -6
batch2_dx4.12_dy1.0_4 6 6 6 1 -2 -1