Would like to count the number of times a value in the whole column of DF2(DF2$B) recedes below each cell in DF1$A.

Example:

DF1 <- data.frame(Q=c("fun","fun"),
                  A=c(200,700))
DF2 <- data.frame(Z=as.Date(c("2023-10-01","2023-10-02","2023-10-03","2023-10-04")),
                  B=c(600,500,100,800))

Desired Output:

DF1$Counter <- c(1,3)
2

There are 2 answers

0
Onyambu On

Make use of findInterval. Note that you have to sort the DF2$B column first

DF1$Counter <- findInterval(DF1$A, sort(DF2$B))
DF1
    Q   A Counter
1 fun 200       1
2 fun 700       3
0
user11057680 On

an alternative with sapply would be...

DF1$Counter <- sapply(DF1$A, function(x, y) {sum(y < x)}, y = DF2$B)