Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you multiply two unequal length vectors by a factor?

Tags:

r

I have two data frames of differing lengths. There is a unique factor that links the two data frames together. I want to multiply the values in the larger data frame by the matching factor in the smaller data frame. Here is code to demonstrate:

d1 <- data.frame(u = factor(x = LETTERS[1:5]), n1 = 1:5)
d2 <- data.frame(u = factor(x = rep(x = LETTERS[1:5], each = 2)), n2 = 1:10)

I want d2[1:2, 2] both multiplied by d1[1, 2] because the factor "A" matches and so forth for the rest of the matching factors.

like image 709
timothy.s.lau Avatar asked Feb 12 '23 17:02

timothy.s.lau


1 Answers

For this problem you can also use match, which should be somewhat more efficient than the merge/transform approach (particularly if you don't need the data.frame that the latter creates):

d2$n2 * d1[match(d2$u, d1$u), 'n1']

# [1]  1  2  6  8 15 18 28 32 45 50
like image 129
jbaums Avatar answered Mar 07 '23 03:03

jbaums