R - How to Test for Character(0) in If Statement

logical(0) in if statement

logical(0) is a vector of base type logical with 0 length. You're getting this because your asking which elements of this vector equal 0:

> !is.na(c(NA, NA, NA))
[1] FALSE FALSE FALSE
> which(!is.na(c(NA, NA, NA))) == 0
logical(0)

In the next line, you're asking if that zero length vector logical(0) is equal to 0, which it isn't. You're getting an error because you can't compare a vector of 0 length with a scalar.

Instead you could check whether the length of that first vector is 0:

if(length(which(!is.na(c(NA,NA,NA)))) == 0){print('TRUE')}

Selecting character(0) from a list

We can use Filter

Filter(Negate(length), L)

Or another option is sapply

L[!sapply(L, length)]

Or as @MartinMorgan mentioned lengths (introduced in the recent R version) can be used (which would be faster)

L[!lengths(L))

Argument is of length zero in if statement

"argument is of length zero" is a very specific problem that comes from one of my least-liked elements of R. Let me demonstrate the problem:

> FALSE == "turnip"
[1] FALSE
> TRUE == "turnip"
[1] FALSE
> NA == "turnip"
[1] NA
> NULL == "turnip"
logical(0)

As you can see, comparisons to a NULL not only don't produce a boolean value, they don't produce a value at all - and control flows tend to expect that a check will produce some kind of output. When they produce a zero-length output... "argument is of length zero".

(I have a very long rant about why this infuriates me so much. It can wait.)

So, my question; what's the output of sum(is.null(data[[k]]))? If it's not 0, you have NULL values embedded in your dataset and will need to either remove the relevant rows, or change the check to

if(!is.null(data[[k]][[k2]]) & temp > data[[k]][[k2]]){
#do stuff
}

Hopefully that helps; it's hard to tell without the entire dataset. If it doesn't help, and the problem is not a NULL value getting in somewhere, I'm afraid I have no idea.

Determine if 3rd digit in string is 0 in R

We can use substring to get characters from specific position.

substring(x, 3, 3) == 0 | substring(x, 3, 4) == 56
#[1] FALSE FALSE TRUE

Just as you have explained it substring(x, 3, 3) == 0 checks if 3rd digit is 0 OR (|) 3rd and 4th digit substring(x, 3, 4) is 56 respectively.

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

You could use ?length:

isEmpty <- function(x) {
return(length(x)==0)
}

input <- c(3, 12);

if (!isEmpty(setdiff(input, 1:9))) {
stop ("not valid")
}


Related Topics



Leave a reply



Submit