A riff on Mark's answer (borrowing his abbreviations), except it uses match
instead of merge as that is often much faster for N-1 joins:
d[, -1] <- d[, -1] * s[match(d[, 1], s[, 1]), -1]
which produces
# Batch A B
# 1 Q 23.23 13.10
# 2 Q 22.22 14.41
# 3 R 24.30 14.64
# 4 R 23.40 15.86
# 5 S 22.88 15.26
# 6 S 24.96 16.35
match
finds the position of a value in the first vector, in the second vector, which effectively allows to do N-1 merges as is the case here. And as I noted, it's faster, which may matter if you have large tables you're joining:
library(microbenchmark)
microbenchmark(s[match(d[, 1], s[, 1]), -1])
# Unit: microseconds
# min lq median uq max neval
# 167.854 173.706 176.6315 181.019 279.025 100
microbenchmark(merge(d[ ,1, drop=F], s, "Batch"))
# Unit: microseconds
# min lq median uq max neval
# 983.353 1060.149 1068.195 1103.302 2181.004 100
Side note, if you have large tables, you should consider data.table
for merges, as that can be even faster than match
, under some circumstances.