Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply each column of a data frame by the corresponding value of a vector [duplicate]

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?

like image 868
DeltaIV Avatar asked Apr 03 '17 15:04

DeltaIV


1 Answers

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)]
like image 131
akrun Avatar answered Nov 15 '22 12:11

akrun