gpt4 book ai didi

r - R 中 'Everything that exists is an object' 的真正含义是什么?

转载 作者:行者123 更新时间:2023-12-03 11:35:10 25 4
gpt4 key购买 nike

我看见:

“To understand computations in R, two slogans are helpful:

• Everything that exists is an object.
• Everything that happens is a function call."

— John Chambers



但我刚刚发现:
a <- 2
is.object(a)
# FALSE

实际上,如果变量是纯基类型,则结果 is.object() 将是 FALSE。所以它不应该是一个对象。

那么 R 中“存在的一切都是对象”的真正含义是什么?

最佳答案

函数is.object似乎只看对象是否具有“类”属性。所以它与口号中的含义不同。

例如:

x <- 1
attributes(x) # it does not have a class attribute
NULL
is.object(x)
[1] FALSE
class(x) <- "my_class"
attributes(x) # now it has a class attribute
$class
[1] "my_class"
is.object(x)
[1] TRUE

现在,试图回答你真正的问题,关于口号,这就是我的表达方式。存在于 R 中的一切是一种对象,它是一种可以操作的数据结构。我认为用函数和表达式更好地理解这一点,它们通常不被认为是数据。

引用钱伯斯 (2008) 的话:

The central computation in R is a function call, defined by the function object itself and the objects that are supplied as the arguments. In the functional programming model, the result is defined by another object, the value of the call. Hence the traditional motto of the S language: everything is an object—the arguments, the value, and in fact the function and the call itself: All of these are defined as objects. Think of objects as collections of data of all kinds. The data contained and the way the data is organized depend on the class from which the object was generated.



以这个表达式为例 mean(rnorm(100), trim = 0.9) .在它被评估之前,它是一个非常像任何其他对象的对象。因此,您可以像使用列表一样更改其元素。例如:
call <- substitute(mean(rnorm(100), trim = 0.9))
call[[2]] <- substitute(rt(100,2 ))
call
mean(rt(100, 2), trim = 0.9)

或者取一个函数,比如 rnorm :
rnorm
function (n, mean = 0, sd = 1)
.Call(C_rnorm, n, mean, sd)
<environment: namespace:stats>

您也可以像简单对象(如列表)一样更改其默认参数:
formals(rnorm)[2] <- 100
rnorm
function (n, mean = 100, sd = 1)
.Call(C_rnorm, n, mean, sd)
<environment: namespace:stats>

从钱伯斯(2008 年)再花一点时间:

The key concept is that expressions for evaluation are themselves objects; in the traditional motto of the S language, everything is an object. Evaluation consists of taking the object representing an expression and returning the object that is the value of that expression.



回到我们的调用示例, call是代表另一个对象的对象。求值时,它变成了另一个对象,在本例中是具有一个数字的数值向量:-0.008138572。
set.seed(1)
eval(call)
[1] -0.008138572

这会将我们带到您没有提到的第二个口号,但通常与第一个口号一起出现:“发生的一切都是函数调用”。

再次从钱伯斯(2008 年),他实际上稍微限定了这个陈述:

Nearly everything that happens in R results from a function call. Therefore, basic programming centers on creating and refining functions.



所以这意味着几乎所有发生在 R 中的数据转换是一个函数调用。即使是一个简单的东西,比如括号,也是 R 中的一个函数。 .

所以以括号为例,你实际上可以重新定义它来做这样的事情:
`(` <- function(x) x + 1
(1)
[1] 2

这不是一个好主意,但说明了这一点。所以我想这就是我的总结:R 中存在的一切都是一个对象,因为它们是可以操作的数据。并且(几乎)发生的一切都是一个函数调用,它是对这个对象的评估,它会给你另一个对象。

关于r - R 中 'Everything that exists is an object' 的真正含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376318/

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