r语言中的class,mode和typeof的区别

Python09

r语言中的class,mode和typeof的区别,第1张

首先,mode和typeof可以归为一个类别,class是另外一个类别。mode和typeof描述的是数据在内存中的存储类型;class描述的是对象的类属性(比如马就是一个类,红马或者白马就是子类,张三的白马和李四的红马就是对象,马这个类有什么属性就是类属性,就像颜色,体重等等)

因为历史的原因(更新过好多次,前身是S语言),所以R语言中数据对象的存储类型变化过好多次。mode和storage.mode得到的是一种比较古老的类型,来自于S语言,其中storage.mode比mode要更精确

mode(3L) # numeric

storage.mode(3L) # integer

typeof 是一种最新的查看类型的函数,针对于R语言而非S语言,而且更为精确,更为细致

storage.mode(`identical`) # function

storage.mode(`if`)# function

typeof(`identical`) # closure

typeof(`if`) # special

class和oldClass返回对象的类属性。对于指定类属性的数据对象,class和oldClass的结果是一样的

a=data.frame(1:10)

oldClass(a) # "data.frame"

class(a) # "data.frame"

但是如果没有指定数据对象的类属性,那么oldClass返回NULL,而class会根据数据对象的存储类型(type)与维度属性来自动给出一个类属性

oldClass(3L) # NULL

class(3L) # integer

class(structure(3L, dim=1)) # array

class(structure(3L, dim=c(1,1))) # matrix

mode storage.mode typeof 是一类,检查变量类型,如list integer character等

关系是,从前往后,检查精度越来越细。所以当想看粗类别时,就用mode,看细类别用typeof.

# 此时后两者都能查到最细的程度

mode(1:5) # numeric

storage.mode(1:5) # integer

typeof(1:5) # integer

# 此时只有typeof能查到最细的程度

mode(`+`) # function

storage.mode(`+`) # function

typeof(`+`) # builtin

# 这里稍微解释一下,`+`是一个函数

# 下面两个例子等价

1+2 # 3

`+`(1,2) # 3

class和另外三个不是一个体系

对于有”class”属性的变量,返回的就是这个属性对应的值

对于没有”class”属性的变量,则根据它的类型、维度来确定

# 有"class"属性,只认属性

a <- 1:6

df <-data.frame(a,a+1)

class(df) # data.frame

class(df)<- "abc" # 随便定义一个值

class(df) # abc

#没有属性,根据类型和dim属性

ar <- array(1:4)

attributes(ar) # 数组dim为4

mat <- matrix(1:4)

attributes(mat) # 矩阵dim为4 1 两个值

a <- 1:4 # 没有dim

class(a) # integer

aar <- structure(a,dim=4) # 赋予类似array的dim

class(aar) # array

amat <- structure(a,dim=c(4,1)) # 赋予类似matrix的dim

class(amat) # matrix

class(list(1:4)) # list 不一样类型