[R] Check for is.object
Phil Spector
spector at stat.berkeley.edu
Mon Nov 22 17:58:30 CET 2010
Santosh -
The simple answer to your question is to initialize
NewObject to NULL before the loop, i.e.
newObject = NULL
However, I should point out this is one of the most
inefficient ways to program in R. A far better way is
to allocate enough space for NewObject outside your
loop, and "fill it in" in the loop. Here's a simple
example to give you an idea of the difference in time
the two methods require:
> system.time({answer = matrix(NA,1000,5);
+ for(i in 1:1000)answer[i,] <- sample(10,5)})
user system elapsed
0.020 0.000 0.017
> system.time({answer=NULL;
+ for(i in 1:1000)answer=rbind(answer,sample(10,5))})
user system elapsed
0.072 0.000 0.070
However, it gets even worse if the sample size is larger:
> system.time({answer = matrix(NA,10000,5);
+ for(i in 1:10000)answer[i,] <- sample(10,5)})
user system elapsed
0.184 0.000 0.184
> system.time({answer=NULL;for(i in 1:10000)
+ answer=rbind(answer,sample(10,5))})
user system elapsed
5.492 0.032 5.562
Even if you don't know how big your newObject matrix will
become, it's still far more efficient to overallocate the
matrix and then truncate it at the end.
I'd strongly recommend that you avoid building your matrix
incrementally inside a loop!
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Mon, 22 Nov 2010, Santosh Srinivas wrote:
> Hello,
>
> I am trying to recursively append some data from multiple files into a
> common object
>
> For this, I am using in a loop
>
> NewObject <- rbind(NewObject,tempObject)
>
>
> For the first loop, obviously there is no NewObject ... so I wanted to do
> NewObject <- tempObject[0,]
>
> Now when it loops again I want to put the statement do "NewObject <-
> tempObject[0,]" inside a if statement ... so that it does I can skip it once
> NewObject has been initialized.
>
> But, is.object doesn't seem to work.
>
> What is the alternative check that I can do? And is there a better way to
> achieve what I want?
>
> Thanks,
> S
>
> ______________________________________________
> 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