[R] matrix operation

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Sat Oct 8 00:17:52 CEST 2005


On Fri, 07 Oct 2005 18:01:41 -0400 Dhiren DSouza wrote:

> Hello:
> 
> I have a matrix 'dat' with 2 columns.
> 
> I have the following code:
> 
> for (i in 1:nrows(dat))
> {
>   if (dat[i,1] < dat[i,2])
>     {
>       dat[i,2]<-0
>     }
> 
>    else
>    {
>      dat[i,2]<-1
>    }
> 
> Is there a way to accomplish this without the for loop?

For this setting
  dat[,2] <- as.numeric(dat[,1] >= dat[,2])
seems to work.

For more complicated tasks look at ifelse().

hth,
Z


> Thank you.
> 
> -Dhiren
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list