[英]How to use apply family functions on an array and a matrix instead of a for loop in R?
Is there a way to use apply like functions instead of the for loop in the code below?有没有办法在下面的代码中使用类似应用的函数而不是 for 循环?
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非常感谢
You can use sapply
/ lapply
here :您可以在此处使用sapply
/ lapply
:
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. seq_len(ncol(b))
从1:ncol(b)
seq_len(ncol(b))
创建一个序列,它类似于for
循环中的1:2
并且for
循环和sapply
的代码保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.