[R] appending to a vector
Sarah Goslee
sarah.goslee at gmail.com
Thu Apr 14 17:40:13 CEST 2011
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
More information about the R-help
mailing list