Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

XYZ coordinates to XY Grids

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading