TheBeginner
TheBeginner

Reputation: 29

How to divide each value in a matrix with the max value of the corresponding column

e.g.

m <- matrix(c(1:9),3,3)

the maximum values per column would be ...

n <- matrix(c(3,6,9),1,3)

how can I then perform an operation so that the output is a 3 by 3 matrix with the values: 0.33,0.66,1 in the first column (as the first column is divided by 3) 0.66,0.83,6 in the second column (as the second column is divided by 6) 0.77, 0.88, 9 in the third column (as the third column is divided by 9).

Upvotes: 2

Views: 614

Answers (4)

akrun
akrun

Reputation: 886938

We can replicate 'n' by the col of 'm'

m/n[col(m)]
#         [,1]      [,2]      [,3]
#[1,] 0.3333333 0.6666667 0.7777778
#[2,] 0.6666667 0.8333333 0.8888889
#[3,] 1.0000000 1.0000000 1.0000000

Upvotes: 3

GKi
GKi

Reputation: 39647

You can use sweep:

sweep(m, 2, apply(m, 2, max), "/")
          [,1]      [,2]      [,3]
[1,] 0.3333333 0.6666667 0.7777778
[2,] 0.6666667 0.8333333 0.8888889
[3,] 1.0000000 1.0000000 1.0000000

or subset the max with col:

m / apply(m, 2, max)[col(m)]

or make a Matrix Multiplication with the diag of 1/max:

m %*% diag(1/apply(m, 2, max))

Have a look at: How to divide each row of a matrix by elements of a vector in R

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

With base R, you can use pmax like below

> t((u<-t(m))/do.call(pmax,data.frame(u)))
          [,1]      [,2]      [,3]
[1,] 0.3333333 0.6666667 0.7777778
[2,] 0.6666667 0.8333333 0.8888889
[3,] 1.0000000 1.0000000 1.0000000

Upvotes: 1

dc37
dc37

Reputation: 16178

Using apply:

apply(m, 2, function(x) x / max(x))

          [,1]      [,2]      [,3]
[1,] 0.3333333 0.6666667 0.7777778
[2,] 0.6666667 0.8333333 0.8888889
[3,] 1.0000000 1.0000000 1.0000000

Is it what you are looking for ?

Upvotes: 3

Related Questions