I define list a & ask for the class of the first element alpha:
a <- list(alpha=c(1,2,3), beta=c("cat","dog","duck"), gamma=factor("a","b","a"))
class(a$alpha)
[1] "numeric"
I then ask for a summary of a, which reports class -none- for alpha:
summary(a)
Length Class Mode alpha 3 -none- numeric beta 3 -none- character gamma 1 factor numeric
Questions: (1) why is this? (2) I am a novice to R and to programming. What references would you recommend for the beginner who really wants to understand how R works (besides the R language definition)? I find it hard to understand things like the difference between mode, class, & type. Thank you in advance.
I don't claim to fully understand the why here, but as best I can tell, this is what's going on.
summary.default actually calls oldClass rather than class. Why I'm not sure, although I'm sure there's a good reason.
Somewhat cryptically in ?class we find the following passages:
Many R objects have a class attribute, a character vector giving the names of the classes from which the object inherits. If the object does not have a class attribute, it has an implicit class, "matrix", "array" or the result of mode(x) (except that integer vectors have implicit class "integer"). (Functions oldClass and oldClass<- get and set the attribute, which can also be done directly.)
So what's going on here is that class returns the implicit class (numeric). Note that attr(a$alpha,"class") returns NULL. Since the attribute doesn't exists, oldClass faithfully returns NULL.
As for the differences between mode, type and class, the first two are related, the third is sort of a separate idea. Mode and type are (I think) actually fairly well explained in the documentation. mode tells you the storage mode of an object, but it is relying on the result of typeof, so they are (mostly) the same. Or connected, at least. But the different values that typeof returns are simply collapsed down to a smaller subset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With