[R] How to do a "go to " in a loop in R

Rolf Turner rolf at math.unb.ca
Thu Jul 22 00:02:29 CEST 2004


Well, there ain't no such thing in R ....  And your code doesn't
really make sense anyway.  You talk about ``a[i]'' where a is
apparently a ***matrix*** (with the same number of columns as the
matrix b, but with fewer --- possibly 0 --- rows).  And in such as
setting a[i] has a meaning, but probably not what you want.  And
talking about ``a[i] <- 0'' when i is a running index, running in
this case over the empty set (!!!) doesn't make sense either.

Perhaps what you want to accomplish is along something like the
following lines:

a<-b[s>3,]
if(nrow(a)==0) {
	result <- 0
} else {
	result <- numeric(nrow(a))
        for (i in 1:nrow(a)){
		result[i] <- 1
        }
}

Of course if that's what you're really trying to do, the for-loop
is a silly waste of time.  Instead do

a<-b[s>3,]
if(nrow(a)==0) {
        result <- 0
} else result <- rep(1,nrow(a))

or slightly more elegantly

a<-b[s>3,]
result <- if(nrow(a)==0) 0 else rep(1,nrow(a))

				cheers,

					Rolf Turner
					rolf at math.unb.ca

===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===
You wrote:

> I'm writing a function which involves a loop. What to write in the "?"
> place would allow it skips the "for loop" and goes to  "a[i]<-0".
>  
>  
>  a<-b[s>3,]
> 
>  if (nrow(a)==0) ?????????????
>                  
> 
> 	for (i in 1:nrow(a)){
>   		a[i]<-1
> 	}
>  a[i]<-0
> 
> 
> Lisa Wang
> Cancer Informatics,
> Ontario Cancer Institute/Princess Margaret Hospital, University Health
> Network;
> Email: lisawang at uhnres.utoronto.ca
> Phone: 416 946 4501 ext. 5201
> Fax: 416 946 4619




More information about the R-help mailing list