R语言中,mode和class有何区别

如题所述

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 不一样类型
温馨提示:答案为网友推荐,仅供参考
相似回答