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:
Oh my, you seriously use for loop to do this?
Oh my, just learned it this way online. Is there a better solution, please?
Instead of doing loop, try this
b[,3:5]=b[,3:5]-d[,3:5]
Thanks