Reputation: 3312
I want to create a sequence of random 2D points in R using runif. What is a good way to do that?
This is my current implementation(does not work)
getpoints <- function(n)
{
t <- 1:n;
for (i in 1:n)
{
t[i] <- runif(2,-1,1)
}
return (t)
}
Upvotes: 1
Views: 1043
Reputation: 15415
Just adding to the numerous answers you have here. This one, like @Arun's is easily able to handle more than 2 columns if necessary.:
replicate(2, runif(100))
It may almost be benchmarking time.
Upvotes: 2
Reputation: 21481
To give an overview of this thread, first of all I will show the speeds associated with the several methods used (so you can draw your own conclusion about which is the best), then I will show you how you could use a function; i.e. the way you intended your function probably.
n <- 1000000
> system.time(cbind(runif(n, -1, 1), runif(n, -1, 1)))
user system elapsed
0.28 0.03 0.31
> system.time(matrix(runif(2*n, min = -1, max = 1), ncol = 2))
user system elapsed
0.32 0.00 0.33
> system.time(replicate(2, runif(n, -1, 1)))
user system elapsed
0.26 0.02 0.35
Here is the function, and the time benchmark:
getPoints <- function (N) {
pointMatrix <- matrix(1, nrow = 1000000, ncol = 2)
for (i in 1:N) {
pointMatrix[i, ] <- runif(2, -1, 1) # it needs to run for all columns
}
}
> system.time(getPoints(n))
user system elapsed
17.59 0.04 19.94
>
Upvotes: -1
Reputation: 121618
n <- 5
cbind(runif(n,-1,1),runif(n,-1,1))
[,1] [,2]
[1,] -0.68434317 -0.7772889
[2,] -0.91200792 -0.6408075
[3,] -0.01888610 0.7350491
[4,] 0.01782097 0.9674700
[5,] -0.56707264 -0.9991566
Upvotes: 3