Everyday R Code (18) – matrix calculation

Calculation1

Subtract different value from multiple columns

b <- matrix(rep(1:20), nrow=4, ncol=5)

c <- c(1,2,4)

b

c

 

for(i in 1:nrow(b)) {

b[i,3:5] <- b[i,3:5] – c

}

b

 

Calculation 2

Subtract matrix from matrix from multiple columns

b <- matrix(rep(1:20), nrow=4, ncol=5)

d<(rep(2:21), nrow=4, ncol=5)

b

d

 

for(i in 1:nrow(b)) {

b[i,3:5] <- b[i,3:5] – d[i,3:5]

}

b

 

Codes and Results in R screenshot:

 

4 thoughts on “Everyday R Code (18) – matrix calculation”

Leave a Comment