I have the following code below to try and loop through a sequence and select values below these values in a sequence and find the difference from another value. For large datasets, this can take a long time. Is there a way to vectorize something like this without looping through the sequence to improve performance?
a <- seq(1, 10, by=0.25)
b <- seq(1, 10, by=1)
c <- vector('list', length(b))
i <- 1
for (n in b){
c[[i]] <- sum(n - a[n >= a])
i <- i + 1
}
data.frame(c)
I've tried to use data.table to bin the data and find the difference, but cannot figure out how to calculate the difference from every value less than the bin value.
library(data.table)
min.n <- 1
max.n <- 10
a <- data.table(seq(min.n, max.n, by=0.5))
colnames(a) <- 'a'
b <- seq(min.n+1, max.n+1, by=1)
bins <- findInterval(a$a,b)
a[,bins:= bins+2]
a[, diff:= bins - a]