How can I check if an R object has a certain attribute? For example, I would like to check if a vector has a "labels" attribute. How can I do this? Exists already a function that does that?
my_vector <- c(1, 2, 3)
my_vector_labelled <- `attr<-`(my_vector, "labels", c(a = 1, b = 2, c = 3))
let's assume there is a function named has_attribute(x, attr). The the expected result would be:
> has_attribute(my_vector, "labels")
FALSE
> has_attribute(my_vector_labelled, "labels")
TRUE
Two ways:
%in% names(attributes(..):
"labels" %in% names(attributes(my_vector))
# [1] FALSE
"labels" %in% names(attributes(my_vector_labelled))
# [1] TRUE
is.null(attr(..,"")):
is.null(attr(my_vector, "labels"))
# [1] TRUE # NOT present
is.null(attr(my_vector_labelled, "labels"))
# [1] FALSE # present
(Perhaps !is.null(attr(..)) is preferred?)
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