Re: [R] appending to a vector

From: Sarah Goslee <sarah.goslee_at_gmail.com>
Date: Thu, 14 Apr 2011 11:40:13 -0400

Hi Dirk,

On Thu, Apr 14, 2011 at 4:59 AM, dirknbr <dirknbr_at_gmail.com> wrote:
> 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?

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

-- 
Sarah Goslee
http://www.functionaldiversity.org

______________________________________________
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.
Received on Thu 14 Apr 2011 - 16:06:40 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 14 Apr 2011 - 16:10:30 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive