Hi Dirk,

On Thu, Apr 14, 2011 at 4:59 AM, dirknbr <dirk...@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@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.

Reply via email to