我不明白为什么向量的类别是向量元素的类别,而不是向量本身。
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
中不存在)来检查对象是否具有$dim
或vector
结构。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
为了说明
vec
和mat
具有相同的存储模式,您可以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"
因此,
array
和matrix
都不会解析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/