set.seed(4286)
n <- 4
k <- 5
V <- sample(seq(4), size=k, replace=TRUE)
M <- matrix(rnorm(n*k), ncol=k)
X <- M
for(i in seq(n)){
X[i,] <- round(M[i,]/V, 2)
}
How can I use apply
family to do the same job above instead of using for
loop?
set.seed(4286)
n <- 4
k <- 5
V <- sample(seq(4), size=k, replace=TRUE)
M <- matrix(rnorm(n*k), ncol=k)
X <- M
for(i in seq(n)){
X[i,] <- round(M[i,]/V, 2)
}
How can I use apply
family to do the same job above instead of using for
loop?
This is the apply equivalent. The results need to be transposed by default.
t(apply(M, 1, function(x) round(x/V, 2)))