5

I have the following data frame and vector:

dframe <- as.data.frame(matrix(1:9,3))
vector <- c(2,3,4)

I would like to multiply each column of dframe by the corresponding value of vector. This won't do:

> vector * dframe
  V1 V2 V3
1  2  8 14
2  6 15 24
3 12 24 36 

each row of dframe is multiplied by the corresponding value of vector, not each column. Is there any idiomatic solution, or am I stuck with a for cycle?

DeltaIV
  • 4,773
  • 12
  • 39
  • 86

2 Answers2

10

Here is another option using sweep

sweep(dframe, 2, vector, "*")
#  V1 V2 V3
#1  2 12 28
#2  4 15 32
#3  6 18 36

Or using col

dframe*vector[col(dframe)]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    I like the second option best. I think it's faster, if you get hooked and want to try it out on a sequence of similar operations :) In my case, after multiplying `dframe` by `vector`, I also want to add `center` to it (another vector). With this approach I can just write `vec2mat <- col(dframe); dframe*vector[vec2mat] + center[vec2mat]`. – DeltaIV Apr 03 '17 at 20:08
1

You can use Map:

as.data.frame(Map(`*`, dframe, vector))

#  V1 V2 V3
#1  2 12 28
#2  4 15 32
#3  6 18 36
Psidom
  • 209,562
  • 33
  • 339
  • 356