Skip to contents

Check that x is zero-length

Usage

is_zerolength(x)

Arguments

x

object to test.

Value

TRUE or FALSE indicating if x is a zero-length object.

Details

No check is performed on dimensions, such that a matrix() with zero rows is a zero-length object whereas a data.frame() with zero rows is not (see the Examples).

Notes

Zero-length() objects can have different types: NULL (NULL), logical (logical(0)), integer (integer(0)), double (numeric(0)), complex (complex(0)), character (character(0)), and list (list() and data.frame()). "" is not a zero-length object: it has a width of zero characters but a length of one. A dataframe with zero rows is not a zero-length object: it has length equal to the number of columns.

is.null() should be used to check that an object is NULL and, more generally, isTRUE(all.equal(x, <zero-length object>)) should be used to check equality to a zero-length object. Testing equality should not be done by using == because that leads to logical(0) if any of the sides contains a zero-length object, which gives an error when used as complete conditional statement.

all(logical(0)), and hence all(numeric(0)) and all(character(0)) that get coerced to type logical, returns TRUE, see the Note in all().

Although zero-length objects are discarded when combined into a vector with other values, their types are taken into account for type coercion, see the vignette mentioned in the See also section. For example, numeric 314 will be coerced to character "314" when it is combined into a vector with zero-length character(0), such that c(314, character(0)) results in the character string "314", not in the numeric value 314. If zero-length objects are combined into a vector with only zero-length values, the type of the vector is the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression, see the section Details in help(c).

See also

The vignettes about design choices and about type coercion.

Other collections of checks on type and length: all_characters(), all_names(), is_logical(), is_natural(), is_number()

Examples

is_zerolength(x = character(0)) # TRUE
#> [1] TRUE
is_zerolength(x = 0) # FALSE
#> [1] FALSE
# A matrix with zero rows is a zero-length object ...
is_zerolength(x = as.matrix(data.frame(a = 314))[numeric(0), , drop = FALSE])
#> [1] TRUE
# ... whereas a dataframe with zero rows is *not* a zero-length object.
is_zerolength(x = data.frame(a = 314)[numeric(0), , drop = FALSE])
#> [1] FALSE

# Zero-length objects affect type coercion.
num <- 314
str(num) # num 314
#>  num 314
zerochar <- character(0)
str(zerochar) # chr(0)
#>  chr(0) 
str(c(num, zerochar)) # chr "314", not num 314
#>  chr "314"