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?
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With