Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test when condition returns numeric(0) in R

Tags:

r

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

like image 310
Bertie Avatar asked May 19 '12 11:05

Bertie


People also ask

How do I check if a number is 0 in R?

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)." } }

Why is R returning numeric 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.


2 Answers

You could use ?length:

isEmpty <- function(x) {     return(length(x)==0) }  input <- c(3, 12);  if (!isEmpty(setdiff(input, 1:9))) {     stop ("not valid") } 
like image 133
sgibb Avatar answered Sep 20 '22 05:09

sgibb


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") } 
like image 40
Tyler Rinker Avatar answered Sep 21 '22 05:09

Tyler Rinker