Skip to content

appending to a vector

3 messages · dirknbr, Sarah Goslee, Jonathan P Daily

#
Hi Dirk,
On Thu, Apr 14, 2011 at 4:59 AM, dirknbr <dirknbr at gmail.com> wrote:
This one. Creating a [vector|matrix|dataframe] of its full final size is
more efficient than growing it incrementally.

But this is likely to be even more efficient, and is shorter and easier
to read:

x2 <- sapply(x, func)

Sarah
#
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:
http://www.R-project.org/posting-guide.html