Let's imagine you would like to construct a simple test based on the condition setdiff(input, 1:9)
.
How can I construct an
if isnotempty(setdiff(input, 1:9)) stop ("not valid")
statement which stops execution when input is c(3, 12)
but continues when input is c(2,5,7)
say? Many thanks, Bertie
fun_int0 <- function(my_data) { # Create user-defined function if(length(my_data) == 0 & is. integer(my_data)) { print("The data object is integer(0).") # [1] "The data object is integer(0)." } else { print("The data object is NOT integer(0).") # [1] "The data object is NOT integer(0)." } }
The numeric0 error in r occurs when you try to access the zeroth position in a numeric vector. It does not occur when dealing with a missing value or a non numeric argument but when dealing with numeric data. If the factor variable does not contain a number, accessing the zeroth position will create a similar result.
You could use ?length
:
isEmpty <- function(x) { return(length(x)==0) } input <- c(3, 12); if (!isEmpty(setdiff(input, 1:9))) { stop ("not valid") }
Here's another option identical(x, numeric(0))
. Here's an example (basically took everything from sgibb and replaced the key line as I'm lazy):
isEmpty <- function(x) { return(identical(x, numeric(0))) } input <- c(3, 12) if (!isEmpty(setdiff(input, 1:9))) { stop ("not valid") }
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