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?
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.
Description. stop stops execution of the current expression, prints the message given as its argument, then executes an error action.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With