首页 > 解决方案 > 为什么我看到 R 向量类的“整数”而不是“向量”

问题描述

为什么从数据框中切片的列的数据类型显示为“整数”而不是“向量”?

df <- data.frame(x = 1:3, y = c('a', 'b', 'c'))
#  x y
#1 1 a
#2 2 b
#3 3 c
c1 <- df[ ,1]
#[1] 1 2 3
class(c1)
#[1] "integer"

标签: rclassvector

解决方案


在 R 中,“类”是对象的属性。但是,在 R 语言定义中,向量不能具有除“名称”之外的其他属性(这就是为什么“因子”不是向量的真正原因)。这里的功能class是给你一个向量的“模式”。

来自?vector

 ‘is.vector’ returns ‘TRUE’ if ‘x’ is a vector of the specified
 mode having no attributes _other than names_.  It returns ‘FALSE’
 otherwise.

来自?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)’ (except that
 integer vectors have implicit class ‘"integer"’).

有关向量“模式”的更多信息,请参见此处,并熟悉另一个惊人的 R 对象:NULL.

要了解“因素”问题,请尝试您的第二列:

c2 <- df[, 2]

attributes(c2)
#$levels
#[1] "a" "b" "c"
#
#$class
#[1] "factor"

class(c2)
#[1] "factor"

is.vector(c2)
#[1] FALSE

推荐阅读