Efficient R coding

Consider the following data frame:

dat <- data.frame(x=c(0,128.96,0,397.37,56.80,0,801.79,340.79),
                  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))
For each value of the column y which satisfies dat$y<=300, I have to do the following algorithm:


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))
I am looking for a more efficient coding that I did with the for loop. Any help is appreciated. Thanks.
Well, it might be helpful, if you provided a word discription (+ formulas in case) of your problem, as well. Sometimes people program very unstraight. However, without knowing what is the aim of your program, I cannot say, if it is efficient for your issue or not.