r - 为什么向量的类别是向量的元素类别而不是向量本身?

标签 r

我不明白为什么向量的类别是向量元素的类别,而不是向量本身。

vector <- c("la", "la", "la")
class(vector) 
## [1] "character"

matrix <- matrix(1:6, ncol=3, nrow=2)
class(matrix) 
## [1] "matrix"

最佳答案

这就是我从中得到的。 class主要用于面向对象的编程,R中还有其他功能可以为您提供对象的存储模式(请参阅?typeof?mode)。

查看?class

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)



看来class的工作方式如下
  • 首先查找$class属性
  • 如果不存在,它将通过检查matrix属性(在array中不存在)来检查对象是否具有$dimvector结构。

    2.1。如果$dim包含两个条目,则将其称为matrix
    2.2。如果$dim包含一个条目或两个以上条目,则将其称为array
    2.3。如果$dim的长度为0,则转到下一步(mode)
  • 如果$dim的长度为0,并且没有$class属性,则执行mode

  • 所以根据你的例子
    mat <- matrix(rep("la", 3), ncol=1)
    vec <- rep("la", 3)
    attributes(vec)
    # NULL
    attributes(mat)
    ## $dim
    ## [1] 3 1
    

    因此,您可以看到vec不包含任何属性(有关说明,请参见?c?as.vector)

    因此,在第一种情况下,class执行
    attributes(vec)$class
    # NULL
    length(attributes(vec)$dim)
    # 0
    mode(vec)
    ## [1] "character"
    

    在第二种情况下,它会检查
    attributes(mat)$class
    # NULL
    length(attributes(mat)$dim)
    ##[1] 2
    

    它看到该对象具有两个维度,可以调用它matrix
    为了说明vecmat具有相同的存储模式,您可以
    mode(vec)
    ## [1] "character"
    mode(mat)
    ## [1] "character"
    

    例如,您还可以看到与数组相同的行为
    ar <- array(rep("la", 3), c(3, 1)) # two dimensional array
    class(ar)
    ##[1] "matrix"
    ar <- array(rep("la", 3), c(3, 1, 1)) # three dimensional array
    class(ar)
    ##[1] "array"
    

    因此,arraymatrix都不会解析class属性。例如,让我们检查data.frame的功能。
    df <- data.frame(A = rep("la", 3))
    class(df)
    ## [1] "data.frame"
    
    class是从哪里获得的?
    attributes(df)    
    # $names
    # [1] "A"
    # 
    # $row.names
    # [1] 1 2 3
    # 
    # $class
    # [1] "data.frame"
    

    如您所见,data.fram设置了$class属性,但这可以更改
    attributes(df)$class <- NULL
    class(df)
    ## [1] "list"
    

    为什么是list?因为data.frame没有$dim属性(两者都不是$class属性,因为我们刚刚删除了它),所以class执行mode(df)
    mode(df)
    ## [1] "list"
    

    最后,为了说明class的工作原理,我们可以手动将class设置为我们想要的任何值,然后看看它将为我们带来什么
    mat <- structure(mat, class = "vector")
    vec <- structure(vec, class = "vector")
    class(mat)
    ## [1] "vector"
    class(vec)
    ## [1] "vector"
    

    关于r - 为什么向量的类别是向量的元素类别而不是向量本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24052158/

    相关文章:

    r - 获取数据的概率密度

    r - 使用 R 进行 Tableau 关联

    r - R中成对距离列表的距离矩阵

    r - 使用 doparallel 在 foreach 循环内循环

    r - 每个时间步的平均值

    r - 使用 ggplot 的 100% 堆叠区域

    r - R 中矩阵的每一行与另一个矩阵的叉积

    r - 如何将列传递给arrange()和mutate()

    R:knitr + RGL:visreg 的 visreg2d 函数存在问题

    r - 如何将列表保存到文件并再次读取(在 R 中)?