Reputation: 7575
Note- The related question does not explain why attr(myVar, "class")
returns NULL
but not list
(and why class(myVar)
returns list
). What is the stander way in R to check the class of an object?
How do I find out if an object is "my custom class" or is a "list" of "my custom class" objects?
foo <- function(x) {
a=list(x=x)
attr(a, "class") <- "myclass"
return(a)
}
newVar = list(foo(10),foo(20))
Now I want to find out what class of newVar
.
attr(newVar, "class") # NULL, but not list!
#NULL
##however this works fine
attr(newVar[[1]], "class")
#[1] "myclass"
Why is it so? What is the correct way to determine class in R?
Upvotes: 2
Views: 21462
Reputation: 132706
The "correct way" to determine the S3 class of an object is using function class
.
Implicit classes:
class(list(1))
#[1] "list"
class(1:5)
#[1] "integer"
Explicit classes:
class(list(1))
class(lm(Sepal.Length ~ Sepal.Width, data = iris))
#[1] "lm"
x <- 1:5
class(x) <- "myclass"
class(x)
#[1] "myclass"
Since a list can contain anything, you have to loop through it to find out the classes of the objects inside it, e.g., sapply(yourlist, class)
.
The class ID is stored as an attribute (as are names, dimensions and some other stuff), but usually you don't need to worry about such internals, since R offers accessor functions.
Upvotes: 4