[R] Construct a data.frame in a FOR-loop

Kristel Joossens kristel.joossens at econ.kuleuven.ac.be
Sun Dec 4 17:10:30 CET 2005


Serguei Kaniovski wrote:
> Say I have a FOR-loop for computing powers (just a trivial example)
> for(i in 1:5)
> {
> 	x<-i^2
> 	y<-i^3
> }
> 
> How can I create a data.frame and a 3D plot of (i,x(i),y(i)), i.e. for 
> each iteration

First of all you can easily avoid for-loops in such examples.
You can better work with matrices, so just do
R> i <- 1:5
R> x <- i^2
R> y <- i^3

Second, maybe very interesting, if you want to look somethimg up and do 
not know the R-command. You can always try with RSiteSearch("...").

I'm not sure what you mean with ``construct a data.frame in a for 
loop''. As far as I know you can better first do the loop and construct 
at the end the data.frame. Anyway, to create a data.frame, you can e.g. do
R> resdf <- as.data.frame(cbind(i,x,y))

To create 3D-plot there are seeral possibilities.
Try   ?persp (for surfaces)
or you can download the scatterplot3d package available on CRAN (for 
points and lines).

Hopefully this helps,
Good luck,
Kristel

Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm




More information about the R-help mailing list