Getting values ​​from indicator variables in R

At first I had to model the coordinates of two points in a rectangle of 20 m X 30 m. Obviously, these points follow a uniform distribution, so this is the first part of my code:

    X1 <- runif(1,0,20)
    X2 <- runif(1,0,30)
    point1 <- c(X1,X2)
    point1

I used the same code for the second point ("point2"), but replaced X1 and X2 with Y1 and Y2 respectively.

Then I had to find the distance between two points:

    distance <- sqrt(((X1-Y1)^2)+((X2-Y2)^2))

Now, if I define A as an event, where the points are within 5 to 10 m from each other, I need to find the indicator variable of this event. This is what I got, but I'm not sure if this is correct:

    x=0
    if (distance < 10 & distance > 5)
    {
     x=1
    }
    Z <- c(distance,x)

If I repeated these commands 1000 times, how would I save the values ​​in each simulation and find the maximum and minimum separation values ​​of 1000 repetitions?

+1
2

- X1 X2 Y1, . , :

 points <- cbind(X1, X2)

, X1 X2 "" , , .

R-:

points1 <- matrix( runif(2000), ncol=2)
points1 <- matrix( runif(2000), ncol=2)
dists <- rowSums( (points1-points2)^2 )
Z <- dists <10 & dists >5
0

. ifelse . 1000 , , runif 1000 . c(X1 , X2), ...

#Just make 1000 calls to runif 
X1 <- runif(1000,0,20)
X2 <- runif(1000,0,30)
Y1 <- runif(1000,0,20)
Y2 <- runif(1000,0,30)
distance <- sqrt(((X1-Y1)^2)+((X2-Y2)^2))

head(distance)
#[1]  9.050522 19.512849 10.413407  7.736564  2.742174 13.729397

# gives 1 if points are within 5 to 10m of each other
event <- ifelse ( distance >= 5 & distance <= 10 , 1 , 0 )

#Or even better, from @GavinSimpson comment just use a vectorised form (we use as.nuemric to turn TRUE / FALSE into 1 and 0, but you could leave that out if you wish)
event <- as.numeric( distance >= 5 & distance <= 10 )

head( event )
#[1] 1 0 0 1 0 0

# And the minimum and maximum sepration distance of those events
min(distance[distance >= 5 & distance <= 10])
#[1] 5.017296
max(distance[distance >= 5 & distance <= 10])
#[1] 9.989868
0

All Articles