[R] loop question
Joshua Wiley
jwiley.psych at gmail.com
Tue Apr 5 17:56:08 CEST 2011
Dear Thomas,
On Tue, Apr 5, 2011 at 8:33 AM, Thomas <thomas.triebs at cantab.net> wrote:
> Dear all,
>
> I am trying to set up a list with 1:c objects each meant to capture the
> coefficients for one coefficient and 100 replications. I receive the
> following error message:
>
> Error in betaboot[[p]] : subscript out of bounds.
>
> My code is below. Where is my mistake?
>
> Many thanks,
>
> Thomas
>
> _________________________________
> betaboot<-list(NULL)
if you know the number of bootstraps (which you seem to later on), a
preferred way to instatiate the list would be:
betaboot <- vector(mode = "list", length = yourlength)
>
> for (i in 1:c) {
because "c()" is such an important function, I would strongly
encourage you not to use it also as a variable.
> betaboot[[i]]<-cbind()
Don't use this to build an empty list.
> }
>
>
> num <- 100 # this is the number of bootstraps
>
> for (i in 1:num) {
>
> [BOOTSTRAP]
>
> coef.temp <- coef(model.temp, data=newdata)
>
> for (p in 1:c){
> betaboot[[p]] <- cbind(betaboot[[p]], coef.temp[,p])
This should work assuming betaboot is instatiated properly. That
said, it looks like you have a nested for loop and then just keep
cbind()ing each element of betaboot bigger and bigger. You may get a
performance increase if you also instantiate each matrix/dataframe
inside betaboot. Then the call would become something like:
betaboot[[i]][,p] <- coef.temp[,p]
that is, you can use a chained series of extraction operators to get
to the appropriate column in the matrix/dataframe inside the
appropriate list element. Then rather than constantly using cbind(),
you just place coef.temp[,p] where you want it. The only requirement
is that you know the sizes of the matrices/dataframes going in so you
can create empty ones from the get go.
Cheers,
Josh
> }
>
> }
>
> ______________________________________________
> 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.
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/
More information about the R-help
mailing list