Filter R dataframe by another dataframe using a tolerance?

Viewed 156

I have two data frames (A & B) of different lengths. For a given value in A, I want to know if there are values anywhere in B that are within a tolerance of +/- 0.3. It would also be useful to know the position of this value in B.

A<-c(1:10)
B<-c(2.2,15,1.8,4.9,20,14,8.2,33,9.8,41,16)

i.e for A[1] there is no value in B within the tolerance,

but for A[2], the values at B[1] and B[3] are within the tolerance, and so on.

I have experimented with the near function in dplyr, however I can only seem to get it to compare on a row by row basis. Any help would be greatly appreciated!

3 Answers

We can use between

library(purrr)
map(A, ~  B[between(B, .x - 0.3, .x + 0.3)]) %>% 
     flatten_dbl

Here is one idea. result is a list. If there are no any match, the length of the element in the result is 0. Otherwise, result will document the index in B that matches the requirement.

A <- 1:10
B <- c(2.2,15,1.8,4.9,20,14,8.2,33,9.8,41,16)

difference <- list()

for (i in 1:length(A)){
  difference[[i]] <- B - A[i]
}

result <- lapply(difference, function(x) which(x < 0.3 & x > -0.3))

In base R, we can use sapply :

unlist(sapply(A, function(x) B[B >= (x- 0.3) & B <= (x + 0.3)]))
#[1] 2.2 1.8 4.9 8.2 9.8
Related