Search code examples
rggplot2simulation

How do you create evenly spaced coordinates for a given number of points to be set in a data frame in R?


Given an input of 'n' points, how do you create a set of coordinates that represent these points evenly distributed (approximately) inside a two dimensional area (eg. 1m x 1m).

For context:

n = 12 ## number of particles in simulation
separation <- 1/(1+ids) ## Separation distance. Set according to the number of particles and size of box (1m x 1m)
frame_total <- 200 ## number of frames in simulation
df <- expand.grid(frame = 1:frame_total, id = 1:n) ## constructs data frame based on the number of points 
df_length <- nrow(df) 
df$x_pos <- runif(df_length) ## initializing vector of equal length to 'df' for x position
df$y_pos <- runif(df_length) ## initializing vector of equal length to 'df' for y position

I'd like to initialize the position of 'n' particles, before a physics simulation begins. The particles can't start too close to one another. The set of coordinates that represent these initial positions will then go into 'df' as the first frame for each individual particle.

This was my first attempt which works to an extent. Once 'n' becomes too large however, this method breaks down.

## sets the initial x position, evenly spaced across the box
df$x_pos <- if_else(df$frame == 1, (df$id)*spr, df$x_pos)

## sets the initial y position, evenly spaced across the box
df$y_pos <- if_else(df$frame == 1, (df$id)*spr, df$x_pos)

Any help would be appreciated. Thanks in advance.


Solution

  • Here is the solution I ended up going with:

    n <- 10 ## number of particles
    m <- ceiling(sqrt(n))  ## number of rows or columns in the grid
    
    ## create a grid of x and y coordinates
    grid_init <- expand.grid(x = seq(0.1, 0.9, 0.8/m), y = seq(0.1, 0.9, 0.8/m))
    
    ## sample n coordinates from the grid
    coords <- grid_init[sample(nrow(grid_init), n), ]
    
    ## plot the coordinates
    ggplot2::ggplot(coords, aes(x, y))+
      geom_point()
    

    Thanks for all the suggestions.