0

I'd like to multiply the df with coefficients, here is some example data

set.seed(123)
df <- data.frame(var1=sample(0:1,10,TRUE),var2=sample(0:1,10,TRUE),var3=sample(0:1,10,TRUE) )
coef <- c(1,2,3)

df is the variables, the coefs are coeficients. I tried multiplying it by doing the following but i get this

> df*coef
   var1 var2 var3
1     0    2    0
2     0    3    1
3     0    1    0
4     1    0    0
5     0    3    0
6     3    0    0
7     1    2    3
8     2    0    1
9     0    0    0
10    0    0    3

I would have expected column1 to be multiply with 1, column two multiply against value 2 etc.

Is there a way to do this multiplication? Any help greatly appreciated. Thanks

H.Cheung
  • 855
  • 5
  • 12

2 Answers2

2

You could do:

df * coef[col(df)]

or eve

data.frame(t(t(df) * coef))
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Try "df .* coef" to do a bitwise multiplication which multiplies each element by the corresponding element.

Edmund Doyle
  • 103
  • 1
  • 8