How to use apply family functions on an array and a matrix instead of a for loop in R?

Viewed 29

Is there a way to use apply like functions instead of the for loop in the code below?

a <- array(rnorm(100,0,1), c(10, 5, 2)) ; a
b <- matrix(rnorm(20,0,1), 10, 2) ; b 

m <- matrix(NA, 10, 2) ; m
for (i in 1:2){ m[,i] <- fitted(lm(b[,i]~a[,,i])) }
m

Many thanks

1 Answers

You can use sapply/lapply here :

m1 <- sapply(seq_len(ncol(b)), function(i) fitted(lm(b[,i]~a[,,i])))

seq_len(ncol(b)) creates a sequence from 1:ncol(b) which is similar to 1:2 in your for loop and the code inside for loop and sapply remains the same.

Related