[R] loop problem

Jim Lemon jim at bitwrit.com.au
Thu Mar 26 11:54:43 CET 2009


Muhammad Azam wrote:
> Dear R members
> I have a problem regarding storing the lists.
> Let 
> L=number of distinct values of any predictor (say L=5)
> P=number of predictors (say P=20)
>
> g1 <- c()
> for(i in 1:P){
> if(L > 1){
>   for(j in 1:(L-1)){
> g <- ....
> g1[j] <- g
>                        }
>             }
> g2[]=sort.list(g1)
>                 }
>
> Now the question is: What should we use inside brackets of g2[....], whether "i" or some thing else? If L is not greater than 1 then there will be a "NULL" for g2. We don't want to store it in g2, so how can we handle this problem. Looking forward for some help. Thanks and 
>   
Hi Muhammad,
The first thing I would ask is "Why not store NULL in g2[[i]] if that 
element is NULL?". If you do this:

for(i in 1:P) {
 if(L > 1) {
  g1<-rep(NA,L)
  for(j in 1:(L-1)) g1[j]<-...
  g2[[i]]<-sort.list(g1)
 }
}

you will have fewer elements in g2 than you have sets of predictors and 
will then have to match up the sets of predictors with the elements in 
g2. I think you could just test for NULL

is.null(g2[[i]])

later on if you don't want to process these in a subsequent step.

Jim




More information about the R-help mailing list