Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205301

count number of values in colum that are in a certain interval, by subgroup

$
0
0

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.


Viewing all articles
Browse latest Browse all 205301

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>