0

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
e.matt
  • 836
  • 1
  • 5
  • 12
  • 1
    `test.two[test.two[, .I[which.max(Decide_val)], id]$V1]` – Ronak Shah Apr 03 '20 at 09:28
  • @Ronak Shah follow up question, is there way to check if l and r are equal by id in decide val then do a which.max on a different col if they are? – e.matt May 15 '20 at 09:08

0 Answers0