Suppose I have a square of size10x10
, then I divide this square in equal parts, for example, in 4 equal parts (could be other number like 2, 8, 16, ...).
After that, inside a loop I want to choose one of the 4 parts randomly and generate one point in this square. Here I will choose the second square.
min.x = 0
max.x=10
min.y=0
max.y=10
xd = xMax-xMin
yd = yMax-yMin
#generating randomly coordinates at the second square
set.seed(1)
xx_1 = 5*runif(1) + 5; yy_1 = 5*runif(1) + 0
#ploting the big square and the point in the second square just to ilustrate
For this example, if I'll do manually, I could use the following function for each one of the 4 squares:
xx_1 = 5*runif(1)+0; yy_1 = 5*runif(1)+0
xx_2 = 5*runif(1)+5; yy_2 = 5*runif(1)+0
xx_3 = 5*runif(1)+0; yy_3 = 5*runif(1)+5
xx_4 = 5*runif(1)+5; yy_4 = 5*runif(1)+5
Any hint on how can I automatizate to generate a point in a specific square?
Here's a little function that does what you ask. You tell it the size of the square (i.e. the length on one side), the number of pieces you want to cut it into (which should obviously be a square number), and the piece you want a random sample in (numbered left to right, bottom to top, as in your example).
square_sample <- function(size = 10, pieces = 4, n = 1)
{
x_min <- ((n - 1) %% sqrt(pieces)) * size/sqrt(pieces)
y_min <- ((n - 1) %/% sqrt(pieces)) * size/sqrt(pieces)
c(x = runif(1, x_min, x_min + size/sqrt(pieces)),
y = runif(1, y_min, y_min + size/sqrt(pieces)))
}
Test it out on your example: we should get a point with an x value between 5 and 10, and a y value between 0 and 5:
square_sample(size = 10, pieces = 4, n = 2)
#> x y
#> 5.968655 3.254514
Or pick the middle square of a 150 * 150 square cut into 9 pieces. Here we expect both x and y to be between 50 and 100:
square_sample(size = 150, pieces = 9, n = 5)
#> x y
#> 78.47472 97.32562