Joan
Joan

Reputation: 33

How to use apply family functions instead of a for loop on a matrix?

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

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

Upvotes: 1

Views: 81

Answers (1)

Karthik S
Karthik S

Reputation: 11584

Does this answer:

> 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
> 

Data used:

> 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
> 

Upvotes: 1

Related Questions