[R] Using the R commands
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Sun Mar 30 11:56:45 CEST 2003
ripley at stats.ox.ac.uk writes:
> On Sat, 29 Mar 2003, Jonathan Baron wrote:
>
> > On 03/30/03 03:25, Marcus V. Stecklow wrote:
> >
> > >I`m doing a program and it`s have a loop using the for command. inside the
> > >loop i have a variable and in each step of loop she have a new value.
> > >
> > >The question is: How can i store the values and make a table?
> >
> > For example:
> > Squares <- rep(NA,10) # make an empty vector with 10 places
> > for (i in 1:10) Squares[i] <- i^2 # fill it with squares
> > Squares # print it
> >
> > Lots of other ways to do this. For example, you can use
> > Squares <- {}
> > for the first step.
>
> The best idea is start out with a vector of the correct length and the
> correct type (rep(NA, 10) is logical), e.g.
>
> Squares <- numeric(10)
>
> This helps for long vectors by reducing the number of copies made.
> Squares <- {} is equivalent to setting the result to NULL, just more
> obscure.
And also note that many of these cases are more succinctly expressed
using implicit loops, like
Squares <- sapply(1:10,function(x)x^2)
or even
Squares <- sapply(1:10,"^",y=2)
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list