I have a data frame consisting of 400 rows of x, y and z values, and I would like to plot the x column against the y column.
This is what I have got so far:
sample3d = function(n)
{
df = data.frame()
while(n>0)
{
X = runif(1,-1,1)
Y = runif(1,-1,1)
Z = runif(1,-1,1)
a = X^2 + Y^2 + Z^2
if( a < 1 )
{
b = (X^2+Y^2+Z^2)^(0.5)
vector = data.frame(X = X/b, Y = Y/b, Z = Z/b)
df = rbind(vector,df)
n = n- 1
}
}
df
}
sample3d(400)
If you need to draw random points on the surface of a sphere, you need just to extract the polar coordinates. Something like that:
sample3d_v2 <- function(n) {
phi<-runif(n,0,2*pi)
cost<-runif(n,-1,1)
sint<-sqrt(1-cost^2)
data.frame(X=sint*cos(phi),Y=sint*sin(phi),Z=cost)
}
Just some tests:
system.time(old<-sample3d(4000))
# user system elapsed
# 3.895 0.000 3.879
system.time(new<-sample3d_v2(4000))
# user system elapsed
# 0.000 0.000 0.002
As you can see, a gain of thousands of times. Test the results are correct:
require(rgl)
plot3d(old)
open3d();plot3d(new)
Regarding your question: just name the object resulting for your function and plot the X and Y components.
data<-sample3d_v2(400)
plot(data$X,data$Y)