I have two data frames:
dfAhas 10 observations per row.dfBhas the corresponding price on all the individual observations.
My task is to look at any 2 rows in dfA, figure out which elements are in both rows, sum up the price of the matching items, and store the results in new dataframe, dfC.
For example, say we have in dfA:
row 1: A, B, C, X, X, X, X, X, X, X
row 2: Z, Z, A, Z, C, Z, Z, B, Z, Z
and in dfB:
A, 63
B, 22
C, 99
...
The overlap in rows 1 and 2 is A, B, and C, so I'd want (63 + 22 + 99) / 1000 in dfC[1, 2] and dfC[2, 1].
The following code does what I need it do, but it is not efficient as n gets large. My actual dfA has over 1000 rows and it can take about 10 minutes to run, so I'm looking ways to write this more efficiently.
set.seed(42)
n <- 10
dfA <- data.frame(replicate(10 ,sample(LETTERS,n,rep=TRUE)), stringsAsFactors = F)
dfB <- data.frame(ID = LETTERS, Price = as.numeric(sample(1:100, 26, replace=FALSE)), stringsAsFactors = F)
overlapPrice <- function (A, B) {
if (A == B) {
return(1)
} else {
x <- intersect(t(dfA[A, ]), t(dfA[B, ]))
return(sum(dfB$Price[match(x, dfB$ID)])/1000)
}
}
dfC <- data.frame(matrix(vector(), n, n))
for (i in (1:n)) {
for (j in (i:n)) {
dfC[i, j] <- overlapPrice(i, j)
dfC[j, i] <- dfC[i, j]
}
}
