gpt4 book ai didi

r - 对R中事物类型的全面考察; 'mode' 和 'class' 和 'typeof' 不足

转载 作者:行者123 更新时间:2023-12-03 06:46:23 36 4
gpt4 key购买 nike

R 语言让我感到困惑。实体有模式,但即使这样也不足以完全描述实体。

这个answer

In R every 'object' has a mode and a class.

所以我做了这些实验:

> class(3)
[1] "numeric"
> mode(3)
[1] "numeric"
> typeof(3)
[1] "double"

到目前为止还不错,但后来我传入了一个向量:

> mode(c(1,2))
[1] "numeric"
> class(c(1,2))
[1] "numeric"
> typeof(c(1,2))
[1] "double"

这没有道理。整数向量肯定应该具有与单个整数不同的类或不同的模式吗?我的问题是:

  • R 中的所有内容都具有(恰好一个)吗?
  • R 中的所有内容都具有(恰好一个)众数吗?
  • “typeof”告诉我们什么(如果有的话)?
  • 完整描述一个实体还需要哪些其他信息? (例如,“向量”存储在哪里?)

更新:显然,文字 3 只是长度为 1 的向量。没有标量。好的但是...我尝试了 mode("string") 并得到了 "character",这让我认为字符串是字符向量。但如果这是真的,那么这应该是真的,但事实并非如此! c('h','i') == "hi"

最佳答案

我同意 R 中的类型系统相当奇怪。之所以会这样,是因为它已经进化了(很长)一段时间......

请注意,您错过了又一个类似类型的函数 storage.mode,以及又一个类似类的函数 oldClass

因此,modestorage.mode 是旧式类型(其中 storage.mode 更准确),而 typeof 是更新、更准确的版本。

mode(3L)                  # numeric
storage.mode(3L) # integer
storage.mode(`identical`) # function
storage.mode(`if`) # function
typeof(`identical`) # closure
typeof(`if`) # special

那么class就完全是另外一个故事了。 class 主要只是对象的 class 属性(这正是 oldClass 返回的内容)。但是当没有设置class属性时,class函数会根据对象类型和dim属性组成一个类。

oldClass(3L) # NULL
class(3L) # integer
class(structure(3L, dim=1)) # array
class(structure(3L, dim=c(1,1))) # matrix
class(list()) # list
class(structure(list(1), dim=1)) # array
class(structure(list(1), dim=c(1,1))) # matrix
class(structure(list(1), dim=1, class='foo')) # foo

最后,类可以返回多个字符串,但前提是类属性是这样的。第一个字符串值是主类的一种,下面的值是它继承的内容。弥补类的长度始终为 1。

# Here "A" inherits from "B", which inherits from "C"
class(structure(1, class=LETTERS[1:3])) # "A" "B" "C"

# an ordered factor:
class(ordered(3:1)) # "ordered" "factor"

关于r - 对R中事物类型的全面考察; 'mode' 和 'class' 和 'typeof' 不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8855589/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com