[R] if else in R

Ben Tupper btupper at bigelow.org
Wed Nov 20 03:54:43 CET 2013


Hi,

On Nov 19, 2013, at 9:41 PM, 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
> 

As a follow up, you could make a logical index for the condition as Nick suggests.

a<-c(1,2,3,4)
b<-c(2,0,5,0)
ab<-data.frame(a,b)
ix <- ab[,'b'] > 0
ix
# [1]  TRUE FALSE  TRUE FALSE

ab[ix,'c'] <- ab[ix,'a']/ab[ix,'b']
ab[!ix,'c'] <- 0
ab
#  a b   c
# 1 1 2 0.5
# 2 2 0 0.0
# 3 3 5 0.6
# 4 4 0 0.0

I'm not a big fan of the ab$b form of subsetting, I find ab[,'b'] more readable for my fading eyesight.  But you could do it your way, too.

ab$c[ix] <- ab$a[ix]/ab$b[ix]

Cheers,
Ben


> 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
>> PLEASE do read the posting guide 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
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org



More information about the R-help mailing list