I'm doing something wrong in the following code, as the column selection does not seem to be by subgroup. Can't figure it out.
library(data.table)
time <- c(1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3)
mass <- c(2,2,2,2,2,2,2,5,5.1,4.9,5,5,5,10,10,10)
expected_check <- c(7,7,7,7,7,7,7,6,6,6,6,6,6,2,2,1)
dt <- data.table(time, mass, expected_check)
dt[, check:= sapply(mass, function(i) length(dt[,mass] <= (i+0.5) & dt[,mass] >= (i-0.5))), by = time]
I would like to check for every mass value, how many values I have in the mass column in the interval defined, at the same time. I think dt[,mass] selects the whole column and does not follow the final by = time. Everything that I've tried suffers from the same issue.