Search code examples
arraysrapplyindices

How do I apply a function to the indices of an array?


I want to apply a function to an array using the indices of the array element. For example if I have an array ar, I would like to compute ar[x,y] <- x + y.

Using nested for for loops this is easy. I want to use an apply function to complete this task.

ar <- array(data = 1, dim = c(2,2))
for(i in 1:2 ){
  for(j in 1:2){
    ar[i,j] <- i +j
  }
}
ar

Solution

  • If it is two-dimensional array, or matrix, you can do:

    row(ar) + col(ar)
    #      [,1] [,2]
    # [1,]    2    3
    # [2,]    3    4