Search code examples
rclasstypesstoragemode

Can mode(), storage.mode() or typeof() return "S3"? Why or why not? (They can return "S4"!)


One can get S4 as the result of either of mode(), storage.mode(), typeof() as is shown below. So, what about the same for S3? Why or why not?

storing <- function(x) {print(c(class(x), mode(x), storage.mode(x), typeof(x)))}

setClass("dummy", representation(x="numeric", y="numeric"))

S4DummyObject = new("dummy", x=1:20, y=rnorm(20))

storing(S4DummyObject) # "dummy" "S4"    "S4"    "S4" 

Solution

  • As for typeof(), "mode(x), storage.mode(x), typeof(x)" don't return S3 since:
    The documentation for typeof() seems pretty clear that the possible values include S4, (but only some S4 objects) and not S3. (as joran stated).
    (The reason is likely that S3 objects are not stored internally in any special way separate from being a thing like a vector or list).

    As for "mode(x), storage.mode(x)", it can be seen via observing what happens if we replicate the situation that we obtained S4 as the returned value from "mode(x), storage.mode(x)".

    new_s3_lst <- function(x, ..., class) {
         stopifnot(is.list(x))
         stopifnot(is.character(class))
         structure(x, ..., class = class)
     } 
    
    new_s3_scalar <- function(..., class) { new_s3_lst(list(...), class = class) }
    
    S3DummyObject = new_s3_scalar(class="dummy")
    class(S3DummyObject) # "dummy"
    storing <- function(x) {print(c(class(x), mode(x), storage.mode(x), typeof(x)))}
    storing(S3DummyObject) # "dummy" "list"  "list"  "list"
    

    So, one can obtain dummy, S4, S4, S4 respectively as the returned value of class(x), mode(x), storage.mode(x), typeof(x); but for S3, at most dummy, list, list, list respectively can be obtained from class(x), mode(x), storage.mode(x), typeof(x).