问题
Firstly I had to model the coordinates of two points in a 20m X 30m rectangle. 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 the X1 and X2 with Y1 and Y2 respectively.
I then had to find the distance between the two points:
distance <- sqrt(((X1-Y1)^2)+((X2-Y2)^2))
Now if I define A as the event where the points are within 5m to 10m of each other, I need to find the indicator variable of this event. This is what I got to, but I'm not sure if it's right:
x=0
if (distance < 10 & distance > 5)
{
x=1
}
Z <- c(distance,x)
If I were to repeat these commands 1000 times, how would I store the values in each simulation and find the min and max separation values in the 1000 reps?
回答1:
At one point you use X1 and X2 and later refer to Y1 which has not been defined. I'm pretty sure you want to use:
points <- cbind(X1, X2)
Context suggests that you wanted to keep the X1 and X2 values in a "parallel" arrangement and defining a matrix rather than a non-dimensioned object will accomplish that.
Last question answered using R's matrix operations:
points1 <- matrix( runif(2000), ncol=2)
points1 <- matrix( runif(2000), ncol=2)
dists <- rowSums( (points1-points2)^2 )
Z <- dists <10 & dists >5
回答2:
Close. Use ifelse or simply a vectorised form to define your event. For 1000 samples all you need to do is use runif to generate 1000 samples. Also there is no need to c(X1 , X2), you can just call them as vectors in your distance calculation...
#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's 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
来源:https://stackoverflow.com/questions/15526782/getting-values-from-indicator-variables-in-r