I have two data frames, below is a small sample of each:
df1 <- data.frame(a1= c(3,4), a2 = c(8, 8), a3 = c(4, 18), a4 = c(9,9), a5 = c(17, 30))
df2 <- data.frame(a1 = c(2,2,2,3,3,3,4,4,4), a2 = c(7,7,7,7,7,7,7,7,7),
a3 = c(4,4,4,4,4,4,4,4,4), a4 = c(10,10,10, 10, 10, 10, 10,10,10),
a5 = c(15,16,17, 15, 16, 17, 15, 16, 17))
I would like to examine, for each row of df1, whether it has "neighbors" in df2, where, by neighbors I mean observations that are different by at most 1 in each column (in absolute value). So for example, row 2 of df2 is a neighbor of row 1 in df1.
The way I currently do this is the following:
sweep(as.matrix(df2), 2, as.matrix(df1[1,]), "-")
For row 1 of df1, and I have to repeat this for each row of df1. Note that df2 and df1 do not have the same number of rows.
However, what I would really like is to avoid doing this "by row", because my data frames have many rows. Is there a way to do it vectorially?