Home > Software engineering >  XYZ coordinates to XY Grids
XYZ coordinates to XY Grids

Time:10-20

I have a list of XY coordinates for fixed positions with given Z values that I want to efficiently fill into an XY grid.

Example code:

x = c(1,1,1,2,2,3,4,5)
y = c(1,2,3,2,4,3,5,5)
z = rep(10,8)

grid = matrix(NA, nrow = max(x), ncol = max(y))
              
#fill the grid for given combinations of X and Y with Z values
for(i in 1:length(x)){
  grid[x[i],y[i]] = z[i]
}

     [,1] [,2] [,3] [,4] [,5]
[1,]   10   10   10   NA   NA
[2,]   NA   10   NA   10   NA
[3,]   NA   NA   10   NA   NA
[4,]   NA   NA   NA   NA   10
[5,]   NA   NA   NA   NA   10

Is there a more efficient way to fill the grid instead of using for-loops?

I tried grid[x,y] = z but that didn't work.

CodePudding user response:

You could create a dataframe with the coordinates to use that to assign these values to your matrix use the following code:

x = c(1,1,1,2,2,3,4,5)
y = c(1,2,3,2,2,3,5,5)
z = rep(10,8)

# Create dataframe of coordinates
df <- data.frame(x = x, y = y)
# Convert to matrix
df.mat <- as.matrix(df)
grid = matrix(NA, nrow = max(x), ncol = max(y))

grid[df.mat] <- z
grid
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]   10   10   10   NA   NA
#> [2,]   NA   10   NA   NA   NA
#> [3,]   NA   NA   10   NA   NA
#> [4,]   NA   NA   NA   NA   10
#> [5,]   NA   NA   NA   NA   10

Created on 2022-10-19 with reprex v2.0.2

CodePudding user response:

Behold the beauty of mapply

mapply(function(x, y, z) { grid[x, y] <<- z }, x, y, z)

grid
     [,1] [,2] [,3] [,4] [,5]
[1,]   10   10   10   NA   NA
[2,]   NA   10   NA   NA   NA
[3,]   NA   NA   10   NA   NA
[4,]   NA   NA   NA   NA   10
[5,]   NA   NA   NA   NA   10
  • Related