简体   繁体   中英

Why do I see “integer” rather than “Vector” for the class of an R vector

Why is the data type of a column sliced from a data frame shown as "integer" instead of "Vector"?

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"

In R, "class" is an attribute of an object. However, in R language definition, a vector can not have other attributes than "names" (this is really why a "factor" is not a vector). The function class here is giving you the "mode" of a vector.

From ?vector :

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

From ?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"’).

See Here for a bit more on the "mode" of a vector, and get yourself acquainted with another amazing R object: NULL .

To understand the "factor" issue, try your second column:

c2 <- df[, 2]

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

class(c2)
#[1] "factor"

is.vector(c2)
#[1] FALSE

Because that is the type. It is a vector of integer s. :)

see

?vector

and

?integer

~ J

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM