Say I have a tibble named `a'. It has three classes:
class(a)
"tbl_df" "tbl" "data.frame"
How can I extract just one of these classes?
a$data.frame
does not work.
Another example is a haven_labelled
object, b
which has three classes:
class(b)
"haven_labelled" "vctrs_vctr" "double"
How can I extract just the double part of b
?
class()
results in an unnamed character vector, which you usually subset using numeric indeces x[i]
, e.g. class(b)[3]
to obtain double"
.
However you could apply string matching, and write an own my_class()
function which is based on a vector of valid class definitions.
valid <- c("data.frame", "double", "character")
my_class <- function(x) {k <- class(x);k[k %in% valid]}
my_class(a)
# [1] "data.frame"
my_class(b)
# [1] "double"
Data:
a <- tibble::as_tibble(data.frame())
b <- haven::labelled()