目前,我对原始数据类型(如数字或字符)和r中的类之间的关系有点困惑。可以合理地说,原始数据类型是r中的内置类,其操作(如+或-)对应于内置方法吗?原始数据类型是否也在内部实现为类(不像java区分原始数据类型和 Package 类)?
hs1ihplo1#
类型和类是不同的概念。类型主要对应于底层c代码中使用的数据类型。引用r语言定义第2章:r特定函数typeof返回r对象的类型。注意,在r下面的c代码中,所有对象都是指向typedef sexprec结构的指针;不同的r数据类型在c中用sexptype表示,sexptype决定了如何使用结构各个部分中的信息。相反,类是一个r概念。注意,r有几个不同的oop系统,其中主要的是s3类。令人困惑的部分可能是,存在与数据类型相对应的隐式类(r中的所有内容都有显式或隐式s3类)。以data.frames为例:
# create an object of type "list"x <- list(a = 1, b = 2)typeof(x)# [1] "list"class(x)# [1] "list"# this is an implicit classattributes(x)# $names# [1] "a" "b"# no class attributeclass(x) <- "data.frame" attr(x,"row.names") <- 1L# don't create data.frames this way, I only do this for didactic reasonsx# a b# 1 1 2attributes(x)# $names# [1] "a" "b"# # $class# [1] "data.frame"# # $row.names# [1] 1is.data.frame(x)# [1] TRUEclass(x)# [1] "data.frame"# this is an explicit classtypeof(x)# [1] "list"# still the same type
# create an object of type "list"
x <- list(a = 1, b = 2)
typeof(x)
# [1] "list"
class(x)
# this is an implicit class
attributes(x)
# $names
# [1] "a" "b"
# no class attribute
class(x) <- "data.frame"
attr(x,"row.names") <- 1L
# don't create data.frames this way, I only do this for didactic reasons
x
# a b
# 1 1 2
#
# $class
# [1] "data.frame"
# $row.names
# [1] 1
is.data.frame(x)
# [1] TRUE
# this is an explicit class
# still the same type
1条答案
按热度按时间hs1ihplo1#
类型和类是不同的概念。类型主要对应于底层c代码中使用的数据类型。引用r语言定义第2章:
r特定函数typeof返回r对象的类型。注意,在r下面的c代码中,所有对象都是指向typedef sexprec结构的指针;不同的r数据类型在c中用sexptype表示,sexptype决定了如何使用结构各个部分中的信息。
相反,类是一个r概念。注意,r有几个不同的oop系统,其中主要的是s3类。令人困惑的部分可能是,存在与数据类型相对应的隐式类(r中的所有内容都有显式或隐式s3类)。
以data.frames为例: