Reputation: 1409
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
Upvotes: 3
Views: 1441
Reputation: 76402
Use attributes
.
my_vector <- c(1, 2, 3)
my_vector_labelled <- `attr<-`(my_vector, "labels", c(a = 1, b = 2, c = 3))
attributes(my_vector)
#> NULL
names(attributes(my_vector_labelled))
#> [1] "labels"
has_attribute <- function(x, which){
which %in% names(attributes(x))
}
has_attribute(my_vector_labelled, "labels")
#> [1] TRUE
Created on 2022-03-31 by the reprex package (v2.0.1)
Upvotes: 2
Reputation: 887118
There is a function available in package
> library(BBmisc)
> hasAttributes(my_vector_labelled, "labels")
[1] TRUE
> hasAttributes(my_vector, "labels")
[1] FALSE
Upvotes: 2
Reputation: 160447
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?)
Upvotes: 6