Why is the class of a vector the class of the elements of the vector and not vector itself?

前端 未结 4 1889
时光说笑
时光说笑 2020-12-16 02:48

I don\'t understand why the class of a vector is the class of the elements of the vector and not vector itself.

vector <- c(\"la\", \"la\", \"la\")
class         


        
4条回答
  •  隐瞒了意图╮
    2020-12-16 03:32

    R needs to know the class of the object you are operating on to perform the appropriate method dispatch on that object. The atomic data type in R is a vector, there is no such thing as a scalar, i.e. R considers a single integer a length one vector; is.vector( 1L ).

    In order to dispatch the correct method R must know the datatype. It's not much using knowing that something is a vector, when your language is implicitly vectorised and everything is designed to operate on a vector.

    is.vector( list( NULL , NULL ) )
    is.vector( NA )
    is.vector( "a" )
    is.vector( c( 1.0556 , 2L ) )
    

    So you can take the return value of class( 1L ) which is [1] "integer" to mean, I am an atomic vector consisting of type integer.

    Despite the fact that under the hood a matrix is actually just a vector with two dimension attributes, R must know it is a matrix so that it can operate row-wise or column-wise on the elements of the matrix (or individually on any single subscripted element). After subsetting, you will return a vector of the datatype of the elements in your matrix, which will allow R to dispatch the appropriate method for your data (e.g. performing sort on a character vector or a numeric vector);

    /* from the underlying C code in /src/main/subset.c....*/
    result = allocVector(TYPEOF(x), (R_xlen_t) nrs * (R_xlen_t) ncs)
    

    You should also note, that before determining the class of an object, R will always check that it is a first a vector, e.g. in the case of running is.matrix(x) on some matrix, x, R checks that it is first a vector, and then it checks for dimension attributes. If the dimension attributes is a vector of INTEGER data types of LENGTH 2 it satisfies the conditions for that object being a matrix (the following code snippet is from Rinlinedfuns.h from /src/include/)

    INLINE_FUN Rboolean isMatrix(SEXP s)
      495 {
      496     SEXP t;
      497     if (isVector(s)) {
      498    t = getAttrib(s, R_DimSymbol);
      499    /* You are not supposed to be able to assign a non-integer dim,
      500       although this might be possible by misuse of ATTRIB. */
      501    if (TYPEOF(t) == INTSXP && LENGTH(t) == 2)
      502        return TRUE;
      503     }
      504     return FALSE;
      505 }
    
    #  e.g. create an array with height and width....  
    a <- array( 1:4 , dim=c(2,2) )
    
    #  this is a matrix!
    class(a)
    #[1] "matrix"
    
    # And the class of the first column is an atomic vector of type integer....
    class(a[,1])
    [1] "integer"
    

提交回复
热议问题