How to multiply each column of a "matrix" by different values

Hi there!!!
My matrix has 6 columns. I want to multiply each column with a different value. Suppose, the first column multiplied by 25674, second column multiplied by 23123, third column multiplied by 675343, etc...
How can I do that? Is there any easy way if I have to multiply in the same way for around 100 columns?

Best,
DC7

This seems a little crazy but it is all I could think of.

MAT <- matrix(1:20, nrow = 4)
MAT
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    1    5    9   13   17
#> [2,]    2    6   10   14   18
#> [3,]    3    7   11   15   19
#> [4,]    4    8   12   16   20
MultVec <- c(2, 0.5, 0.1, 3, 10)
MultMAT <- mapply(FUN = `*`, as.data.frame(MAT), MultVec)
MultMAT
#>      V1  V2  V3 V4  V5
#> [1,]  2 2.5 0.9 39 170
#> [2,]  4 3.0 1.0 42 180
#> [3,]  6 3.5 1.1 45 190
#> [4,]  8 4.0 1.2 48 200

Created on 2020-07-22 by the reprex package (v0.2.1)

1 Like

Hi @FJCC! How can I round of all the values within the dataframe that generated after the multiplication?

Thanks
DC7

MultMAT is a matrix and you can do rounding with the apply() function.

apply(MultMAT, MARGIN = 2, round, digits = 2)

Thanks @FJCC
By the time I have found this works : round(MultMAT, digits=0)

Best,
DC7

How can I multiply all the columns with a constant value (e.g. 1 million) ?

Best
DC7

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.