user121
user121

Reputation: 931

How to multiply each column by each scalar in R?

I have the following variable Q

a = c(1,2,3,4)
b = c(45,4,3,2)
c = c(34,23,12,45)
Q = cbind(a,b,c)

I also have another variable r

r = c(10,20,30)

I would like to multiply each column of Q by each respective value in r (for example, the first column of Q multiplied by first value in r, the second column of Q multiplied by second value in rand so on).

Specifically for this example, the output I am looking for is:

      10   900   1020
      20    80    690
      30    60    360
      40    40   1350

I am new to R and looking for the most optimal way to do this.

Upvotes: 4

Views: 6751

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269431

Try this:

Q %*% diag(r)

giving:

     [,1] [,2] [,3]
[1,]   10  900 1020
[2,]   20   80  690
[3,]   30   60  360
[4,]   40   40 1350

or any of these:

t(t(Q) * r)

Q * r[col(Q)]

sweep(Q, 2, r, "*")

Q * rep(r, each = nrow(Q))

mapply("*", as.data.frame(Q), r)

See this answer for the same question except using division: How to divide each row of a matrix by elements of a vector in R

Upvotes: 11

Onyambu
Onyambu

Reputation: 79188

you will just need to do double transpose:

t(r*t(Q))
      a   b    c
[1,] 10 900 1020
[2,] 20  80  690
[3,] 30  60  360
[4,] 40  40 1350

Upvotes: 0

Related Questions