I have two dataframes of the form
df.f <- data.frame(ID=c("A_1", "A_2", "A_3"), B=c(130, 250, 330))
df.r <- data.frame(ID=c("B_1", "B_2", "B_3"), B=c(170, 350, 480))
I want to pairwise subtract df.f$B from df.r$B (direction is important), and selects those pairs which subtraction value is within a range of 200 and 300.
I know how to outer:
outer(df.r$B, df.f$B, '-')
[,1] [,2] [,3]
[1,] 40 -80 -160
[2,] 220 100 20
[3,] 350 230 150
and could potentially melt the resulting matrix and then select upon the value column, but outer doesnt keep names:
library(reshape2)
res <- melt(as.matrix(outer(df.r$B, df.f$B, '-')))
final <- res[res$value >= 200 & res$value <= 300,]
> final
Var1 Var2 value
2 2 1 220
6 3 2 230
Any idea how to achieve a result in the form of:
Var1 Var2 Diff
A_1 B_2 220
A_2 B_3 230
I guess it can be done with finding the indices in the original table.
Many thanks!