# Generating binary data in shape regions in R

I am trying to figure out how to generate data in a binary classification figure in R.

Two concepts where examples that fall within any of the three 3 × 3 squares are labeled positive and the remaining examples (outside each of the squares but within X) are labeled negative. The position of the point x = (x1,x2) in the upper left-hand corner for each square is shown in the picture. Consider horizontal axis to be x1 and vertical axis as x2.

I need to generate the data from a uniform distribution and labelled according to the rules. I tried the code below, but am not able to figure out how to classify the points and if I am generating them correctly. The image I get is below.

  n <- 250

x <- runif(n, -6, 6)

y <- runif(n, -4, 4)

plot(c(-6, 6), c(-4,4), type = "n", asp=1)

points(x,y, col=2)



Any help will be greatly appreciated. I am a newbie with R and this task is a bit over my head.

• Questions solely about how software works are off-topic here, but you may have a real statistical question buried here. You may want to edit your question to clarify the underlying statistical issue. You may find that when you understand the statistical concepts involved, the software-specific elements are self-evident or at least easy to get from the documentation. Nov 26, 2022 at 23:07

This can be addressed using geometry / spatial tools. We can do this using the sf package pretty easily.

First, you need to make the border (surrounding square).

#> First you need to make a polygon that is the contianer so to speak
library(sf)

border <- matrix(c(
-6, -4,
-6, 4,
6, 4,
6, -4,
-6, -4
), ncol  = 2, byrow = TRUE) |>


Then, you uniformly sample poitns from inside that border / container.

# sample random points
rand_points <- st_sample(border, size = 250)


Instead of recreating those exact squares that you have, I've just created a grid and grabbed 3 of them instead. You could follow the above steps to make your own squares.

# going to make grid and select 3 random ones
squares <- st_make_grid(border, cellsize = c(2, 2))[c(8, 17, 10)]


Now, the positive values are just the intersecting points whereas the negative ones are all of the points not contained in the squares.

# now just find the difference for negative and intersectino for positive
negative_vals <- st_difference(rand_points, squares)
positive_vals <- st_intersection(rand_points, squares)


And you can plot them to verify.

plot(border)