M. Bu
M. Bu

Reputation: 63

Filling matrix with array coordinates in R

I am trying to fill a matrix so that each element will be a string consisting of its coordinates (row, column).

i.e.

[ '1,1' '1,2' '1,3' ]
[ '2,1' '2,2' '2,3' ]
[ '3,1' '3,2' '3,3' ]

I have been able to do this with a square matrix but it is not robust if I vary the number of rows or columns.

This is what I have so far

#Works but only with a square matrix

x <- 20 #Number of rows
y <- 20 #Number of columns
samp <- 200 #Number of frames to sample

grid = matrix(data = NA,nrow = x,ncol = y)

for (iter_col in 1:y){
  for (iter_row in 1:x){
    grid[iter_col,iter_row] = paste(toString(iter_row),toString(iter_col),sep = ',')
  }
}

I am using this to randomly sample a grid which I superimpose on images for a cell counting method. So I do not have any data yet. Not all of these grids will have equal numbers of rows and columns.

Can you help me make this more flexible? My background in R is a little lacking so the solution my be right in front of me...

Thanks!

Edit

My variables in grid[iter_col,iter_row] were in the wrong order. Once they were switched it works for matrices of varying dimensions.

Thanks G5W for catching that error.

Upvotes: 3

Views: 1604

Answers (2)

989
989

Reputation: 12935

I suspect this would be much faster:

matrix(paste0(rep(seq_len(x), times=y), ", ", rep(seq_len(y), each=x)), nrow = x, ncol = y)

     [,1]   [,2]   [,3]   [,4]   [,5]  
[1,] "1, 1" "1, 2" "1, 3" "1, 4" "1, 5"
[2,] "2, 1" "2, 2" "2, 3" "2, 4" "2, 5"
[3,] "3, 1" "3, 2" "3, 3" "3, 4" "3, 5"
[4,] "4, 1" "4, 2" "4, 3" "4, 4" "4, 5"

OR using col and row (as mentioned in the comments by @rawr)

grid[] <- paste0(row(grid), ", ", col(grid))

Upvotes: 1

d.b
d.b

Reputation: 32548

Here's one way using sapply

rows = 4
columns = 5
sapply(1:columns, function(i) sapply(1:rows, function(j) paste(j,i,sep = ", ")))
#     [,1]   [,2]   [,3]   [,4]   [,5]  
#[1,] "1, 1" "1, 2" "1, 3" "1, 4" "1, 5"
#[2,] "2, 1" "2, 2" "2, 3" "2, 4" "2, 5"
#[3,] "3, 1" "3, 2" "3, 3" "3, 4" "3, 5"
#[4,] "4, 1" "4, 2" "4, 3" "4, 4" "4, 5"

Upvotes: 1

Related Questions