Search code examples
rfor-loopmultidimensional-arraysyntax

Iterating over one dimension of a multidimensional array in R


I have an array points of points in 3D space, implemented as a 2D array of dimension (numberOfPoints, 3). I have voxel map of an area and want to find how many points are in each voxel. I'd like to loop through the array and for each point, increment the population of its voxel. But I find that a simple for loop goes through the individual elements of the whole 2D array. That is, this:

for (point in points) {
  print(point)
}

prints a lot of numbers (the individual coordinates). I would like it to print instead a lot of three-element vectors. What is the proper syntax for looping through only one dimension?


Solution

  • You can loop over the dimension. For 2-d we have the handy nrow() and ncol() functions to get the dimension. Generally, you could replace nrow(x) with dim(x)[1]

    for(i in 1:nrow(points)) {
      print(points[i, ]) 
    }
    

    There's also the apply function made for applying a function over a margin of an array:

    apply(points, MARGIN = 1, FUN = print)