Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(R) IF statement: stop & warn if FALSE else continue

Tags:

unit-testing

r

I'm making a function and before it does any of the hard stuff I need it to check that all the column names listed in the 'samples' dataset are also present in the 'grids' dataset (the function maps one onto the other).

all(names(samples[expvar]) %in% names(grids))

This does that: the code within all() asks if all the names in the list ('expvar') of columns in 'samples' are also names in 'grids'. The output for a correct length=3, expvar would be TRUE TRUE TRUE. 'all' asks if all are TRUE, so the output here is TRUE. I want to make an IF statement along the lines of:

if(all(names(samples[expvar]) %in% names(grids)) = FALSE) {stop("Not all expvar column names found as column names in grids")}

No else needed, it'll just carry on. The problem is that the '= FALSE' is redundant because all() is a logically evaluable statement... is there a "carry on" function, e.g.

if(all(etc)) CARRYON else {stop("warning")}

Or, can anyone think of a way I can restructure this to make it work?

like image 489
dez93_2000 Avatar asked Aug 24 '14 23:08

dez93_2000


People also ask

How do I stop an if statement in R?

The R Break statement is very useful to exit from any loop such as For, While, and Repeat. While executing these, if it finds the break statement inside them, it will stop executing the code and immediately exit from the loop.

What does stop () do in R?

Description. stop stops execution of the current expression, prints the message given as its argument, then executes an error action.

How do you stop an execution in if condition?

You put the rest of the block in a sub-block with { } and put else in front of that. You can nest as deeply as you want but you might try factoring out blocks to helper functions to reduce the complexity and give statements a name.


1 Answers

You're looking for the function stopifnot.

However you don't need to implement it as

if (okay) {
  # do stuff
} else {
  stop()
}

which is what you have. Instead you can do

if (!okay) {
  stop()
}
# do stuff

since the lines will execute in sequential order. But, again, it might be more readable to use stopifnot, as in:

stopifnot(okay)
# do stuff
like image 145
shadowtalker Avatar answered Nov 09 '22 23:11

shadowtalker