如何在矩阵上使用应用族函数而不是for循环?

时间:2020-10-14 16:13:48

标签: r for-loop matrix apply lapply

有没有一种方法可以使用Apply系列函数来代替下面的代码中的for循环?

m <- matrix(0, 10, 5)
m
for (i in 2:5) m[,i] <- m[,(i-1)] + 1
m

1 个答案:

答案 0 :(得分:1)

此答案是否正确

> t(apply(m, 1, function(x) x = 0:4))
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    1    2    3    4
 [2,]    0    1    2    3    4
 [3,]    0    1    2    3    4
 [4,]    0    1    2    3    4
 [5,]    0    1    2    3    4
 [6,]    0    1    2    3    4
 [7,]    0    1    2    3    4
 [8,]    0    1    2    3    4
 [9,]    0    1    2    3    4
[10,]    0    1    2    3    4
> 

使用的数据:

> m
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    0    0    0    0
 [2,]    0    0    0    0    0
 [3,]    0    0    0    0    0
 [4,]    0    0    0    0    0
 [5,]    0    0    0    0    0
 [6,]    0    0    0    0    0
 [7,]    0    0    0    0    0
 [8,]    0    0    0    0    0
 [9,]    0    0    0    0    0
[10,]    0    0    0    0    0
> for(i in 2:5) m[,i] <- m[,(i-1)] + 1
> m
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    1    2    3    4
 [2,]    0    1    2    3    4
 [3,]    0    1    2    3    4
 [4,]    0    1    2    3    4
 [5,]    0    1    2    3    4
 [6,]    0    1    2    3    4
 [7,]    0    1    2    3    4
 [8,]    0    1    2    3    4
 [9,]    0    1    2    3    4
[10,]    0    1    2    3    4
>