Reputation: 47
this is probably a really trivial question, but I have not found a workable solution to it yet. There is a similar question posted here, but it did not get a workable answer, so I am grateful for any advice.
I have a simple 3x3 matrix and want to multiply the 2nd column by a fixed factor. Example:
m<-matrix(rep(c(1,2,3),1*3),nrow=3)
m
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 2 2
[3,] 3 3 3
If I try to do m[,2]*5
, it gives me [1] 5 10 15
The result I would like looks like this:
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 2 10 2
[3,] 3 15 3
It can't be that difficult, can it?
Upvotes: 2
Views: 163
Reputation: 263301
I think a more general approach than single column assignment would be a sweep
with the vector c(1,5,1)
:
sweep(m, 2, c(1,5,1), "*")
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 2 10 2
[3,] 3 15 3
Then you could apply a single vector to a matrix and not need to do repeated single column operations:
sweep(m, 2, c(2,5,10), "*")
[,1] [,2] [,3]
[1,] 2 5 10
[2,] 4 10 20
[3,] 6 15 30
@akrun's solution in the comments m*c(1, 5, 1)[col(m)]
seems to do this efficiently, but I had difficulty understanding how it works. It seems to depend on the precedence of operations and would have been easier for me to understand if it had been written: c(1, 5, 1)[col(m)]*m
. That makes it clearer that the vector c(1, 5, 1)[col(m)]
is computed first rather than m*c(2,5,10)
being extracted by [col(m)]
.
Upvotes: 0