Home > Back-end >  How to check if an R object has a certain attribute?
How to check if an R object has a certain attribute?

Time:04-01

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

CodePudding user response:

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?)

CodePudding user response:

There is a function available in package

> library(BBmisc)
> hasAttributes(my_vector_labelled, "labels")
[1] TRUE
> hasAttributes(my_vector, "labels")
[1] FALSE

CodePudding user response:

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)

  •  Tags:  
  • r
  • Related