I have a data.table
test
structure(list(id = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2),
measure = c("l1", "l2", "l3", "r1", "r2", "r3", "l1", "l2",
"l3", "l4", "r1", "r2", "r3"), side = c("l", "l", "l", "r",
"r", "r", "l", "l", "l", "l", "r", "r", "r"), Decide_val = c(120,
122, 125, 135, 133, 124, 150, 148, 144, 146, 140, 138, 133
), Col_1 = 1:13, Col_2 = 13:1), row.names = c(NA, -13L), class = c("data.table",
"data.frame")) -> test
I want to select the last two values based on id
and side
then average these like so
test.two <- test[, lapply(.SD, function(x) mean(tail(x,2))),.SDcols = 4:6,by = list(id,side)]
test.two
id side Decide_val Col_1 Col_2
1: 1 l 123.5 2.5 11.5
2: 1 r 128.5 5.5 8.5
3: 2 l 145.0 9.5 4.5
4: 2 r 135.5 12.5 1.5
Finally I want to by id
keep the value that is highest in Decide_Val
and do this for Col_1
and Col_2
based on Decide_val
Output would be :
id side Decide_val Col_1 Col_2
2: 1 r 128.5 5.5 8.5
3: 2 l 145.0 9.5 4.5