Message-ID: <8B83C83A-4791-4ECE-9740-5711F0AD81B8@comcast.net>
Date: 2013-11-20T03:12:03Z
From: David Winsemius
Subject: if else in R
In-Reply-To: <CAEVDvzV76YjfnuOi-_xkp9h=6sioAQy+oa3UeYa=6KBV6XibTQ@mail.gmail.com>
On Nov 19, 2013, at 5:30 PM, Gary Dong wrote:
> Dear R users,
>
> I am a R beginner and I am having trouble in using "If Else" in R. Here is
> an example:
>
> ## create a data frame
>
> a<-c(1,2,3,4)
> b<-c(2,0,5,0)
> ab<-data.frame(cbind(a,b))
>
> ##calculate c, which is the ratio between a and b
>
> if(ab$b>0) {
> ab$c<-ab$a/ab$b
> } else {
> ab$c<-0
> }
>
> here is the error I got:
Consider this alternative:
ab$c <- (ab >0 ) * ab$a/ab$b
Although in general, you will probably use `ifelse`.
?ifelse # different than ?"if"
--
David Winsemius
Alameda, CA, USA