0

I have a variable b which is of varying length.

Eg. it can be

b=0 or b=c(1,4,5)

I have an if condition stating that if

b=0 then it should do something.

Whenever b is not 0 or is of length larger than 1 I get the warning:

the condition has length > 1 and only the first element will be used

Basically what I would like to have is: if b=0 then do something otherwise do something else REGARDLESS of the length of the vector.

How should I do this properly?

1
  • 2
    That's a warning, not an error. Do you want it to "do something" when b <- c(1,2,0), or should it "do something else"? Commented Jan 1, 2013 at 18:38

2 Answers 2

6

There is an alternative solution using identical, any and all.

From your description I would deduce three scenarios, not sure which one you'll actually need:

  1. Do something only if b==0. If b!=0 or if length(b)>1 then don't do it. TRUE only for b <- 0

    if (isTRUE(identical(b, 0))) {
      # do something
    }
    
  2. Do something if b==0 or if all elements of b are 0. TRUE for b <- 0 and b <- c(0, 0) and b <- c(0, 0, 0) and ...

    if (all(b==0)) {
      # do something
    }
    
  3. Do something if b==0 or if any element of b is 0. TRUE for b <- 0 and b <- c(12, 0, 34, 2, 3) and b <- c(0, 0, 3, 2) and ...

    if (any(b==0)) {
      # do something
    }
    
0

Try %in% as in:

foo <- function(b) {
  if(0 %in% b) {
    ## do something
    writeLines("Zero was in `b`")
  }
}

> b <- 0
> foo(b)
Zero was in `b`
> b <- c(1,4,5)
> foo(b)
> b <- c(b, 0)
> foo(b)
Zero was in `b`

The point here is to check if the thing you are interested in (here 0) is included in the set of items supplied via the vector b.

For the "do something else case you need to extend foo() with an else clause:

foo <- function(b) {
  if(0 %in% b) {
    ## do something
    writeLines("Zero was in `b`")
  } else {
    ## do something else
    writeLines("Zero was not in `b`")
  }
}

> b <- 0
> foo(b)
Zero was in `b`
> b <- c(1,4,5)
> foo(b)
Zero was not in `b`
> b <- c(b, 0)
> foo(b)
Zero was in `b`
2
  • would the negation be if (!0 %in% b) ? meaning if there is no 0 in b? Commented Jan 1, 2013 at 16:40
  • @user1723765 Yes, essentially it would mean "0 is not in b" Commented Jan 1, 2013 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.