'How to check if an R object has a certain attribute?
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
Solution 1:[1]
Two ways:
%in% names(attributes(..):"labels" %in% names(attributes(my_vector)) # [1] FALSE "labels" %in% names(attributes(my_vector_labelled)) # [1] TRUEis.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?)
Solution 2:[2]
There is a function available in package
> library(BBmisc)
> hasAttributes(my_vector_labelled, "labels")
[1] TRUE
> hasAttributes(my_vector, "labels")
[1] FALSE
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | r2evans |
| Solution 2 | akrun |
| Solution 3 |
