# [R] if else in R

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Wed Nov 20 04:02:08 CET 2013

```Which means you should use the ifelse function...

ab\$c <- ifelse( ab\$b>0, ab\$a/ab\$b, 0 )
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
---------------------------------------------------------------------------
Sent from my phone. Please excuse my brevity.

Nick Matzke <matzke at berkeley.edu> wrote:
>Hi,
>
>This would be an issue with if() as well as if/else.  ab\$b has 4
>numbers in it, so ab\$b > 0 evaluates to "TRUE TRUE FALSE TRUE" or
>whatever. if() can only take a single true or false. Cheers! Nick
>
>On Tue, Nov 19, 2013 at 8:30 PM, Gary Dong <pdxgary163 at gmail.com>
>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:
>>
>> Warning message:
>> In if (ab\$b > 0) { :
>>   the condition has length > 1 and only the first element will be
>used.
>>
>> Any help is appreciated!
>>
>> Gary
>>
>>         [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help