[R] Generating random geographical coordinates

R. Michael Weylandt michael.weylandt at gmail.com
Wed Oct 10 17:14:12 CEST 2012


On Wed, Oct 10, 2012 at 4:09 PM, Poizot Emmanuel
<emmanuel.poizot at cnam.fr> wrote:
> Le 10/10/2012 17:02, R. Michael Weylandt a écrit :
>>
>> Change 1 to some other number to get more points from runif()
>>
>> More generally, take a look at "An Introduction to R" and read most
>> everything you can find on the topic of vectorization. If you don't
>> know how to get "An Introduction to R", try typing help.start() at
>> your prompt and it should happen automatically.
>>
>> Cheers,
>> Michael
>>
>> On Wed, Oct 10, 2012 at 3:15 PM, Poizot Emmanuel
>> <emmanuel.poizot at cnam.fr> wrote:
>>>
>>> Dear all,
>>>
>>> I have two coordinates vectors, say X and Y of length n.
>>> I want to generate for each couple of coordinates X1,Y1 X2,Y2
>>> X3,Y3....Xn,Yn
>>> a random coordinate which is located in a square define as X +/- dx and Y
>>> +/- dy.
>>> I saw the runif function which can generate for just one value at a time
>>> what I want  : runif(1, X - dx, X + dx) for X and runif(1, Y - dy, Y +
>>> dy)
>>> for Y.
>>> I would like to know if there is not a more powerfull way in R to
>>> generate
>>> directly the set of random coordinates.
>>> Regards
>>>
>>> --
>>> Emmanuel Poizot
>>>
>
> If I put say 10 as first argument of runif, I will have 10 random values in
> a square of size X - dx, X + dx and Y - dy, Y + dy for example. That not
> want I'm looking for. I would like to have just one random coordinate in
> this square but for each couple of coordinates X1,Y1 X2,Y2 X3,Y3....Xn,Yn.
> Hope it's more clear.
>

Yes,

In that case, just stick your X1, X2, etc. in a vector; same with Y1,
Y2. and pass those to runif() as well. E.g.,

X <- c(1,2,3,4,5)
Y <- c(5,4,3,2,1)

x_points <- runif(5, X-1, X+1)
y_points <- runif(5, Y-1, Y+1)

and it will work. You can even wrap this in a function

points_maker <- function(X, Y, dx = 0.1, dy = dx, n = max(length(X), length(Y)){
   cbind(x = runif(n, X - dx, X + dx), y = runif(n, Y - dy, Y + dy))
}

but it might take you a few hours all of what's going on there.
Reading the tutorial I pushed will certainly help with that as well.

Cheers,
Michael




More information about the R-help mailing list