Consider the following data frame:
For each value of the column y which satisfies dat$y<=300, I have to do the following algorithm:
I am looking for a more efficient coding that I did with the for loop. Any help is appreciated. Thanks.
Code:
dat <- data.frame(x=c(0,128.96,0,397.37,56.80,0,801.79,340.79),
y=c(40,97,172,186,210,246,327,432),
d=c(1,0,0,0,0,1,0,1), A=c(0,1,0,1,1,0,1,1), B=c(0,1,0,1,1,0,1,1))
Code:
res=NULL
for (i in which(dat$y <= 300)){
cond1 <- (dat$y >= dat$y[i])
cond2 <- (dat$y==dat$y[i] & dat$d==1)
A_y <- dat$A * (dat$x <= dat$y[i])
sw <- 1 - A_y + A_y * dat$B / 0.5
res[i] <- (sum(sw * cond2) / sum(sw*cond1))
}