[R] appending to a vector
Jonathan P Daily
jdaily at usgs.gov
Thu Apr 14 17:45:47 CEST 2011
Neither is the fastest method. The best way would be to vectorize func so
that it accepts and returns a vector. Many builtin R functions do this and
say so in their documentation.
The slower way would be to use one of the apply functions, such as:
?lapply
x2 <- lapply(x, func)
If you must use a for loop, your second example is faster since it does
not rewrite x2 each iteration.
An excellent reference on this subject and many other R pitfalls is 'The R
Inferno'
http://lib.stat.cmu.edu/s/Spoetry/Tutor/R_inferno.pdf
--------------------------------------
Jonathan P. Daily
Technician - USGS Leetown Science Center
11649 Leetown Road
Kearneysville WV, 25430
(304) 724-4480
"Is the room still a room when its empty? Does the room,
the thing itself have purpose? Or do we, what's the word... imbue it."
- Jubal Early, Firefly
r-help-bounces at r-project.org wrote on 04/14/2011 04:59:04 AM:
> [image removed]
>
> [R] appending to a vector
>
> dirknbr
>
> to:
>
> r-help
>
> 04/14/2011 11:32 AM
>
> Sent by:
>
> r-help-bounces at r-project.org
>
> Which one is more efficient?
>
> x2=c()
> for (i in 1:length(x)) {
> x2=c(x2,func(x[i]))
> }
>
> or
>
> x2=x
> for (i in 1:length(x)) {
> x2=func(x[i])
> }
>
> where func is any function?
>
> Dirk
>
> --
> View this message in context: http://r.789695.n4.nabble.com/
> appending-to-a-vector-tp3449109p3449109.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list