[1] 16 cube [1] 8 cube(4) # -> [1] 64 在两个-6ren">
gpt4 book ai didi

r - 如何在 R 中使用 "<<-"(范围分配)?

转载 作者:行者123 更新时间:2023-12-03 04:31:17 26 4
gpt4 key购买 nike

我刚刚读完 scoping in the R intro ,并且我很好奇<<-作业。

该手册展示了一个(非常有趣的)<<- 的示例。 ,我觉得我明白了。我仍然缺少的是它何时有用的背景。

所以我很想从您那里读到有关何时使用 <<- 的示例(或示例链接)。可能很有趣/有用。使用它可能存在哪些危险(看起来很容易被忽视),以及您可能想分享的任何提示。

最佳答案

<<-与闭包结合使用以维持状态最有用。这是我最近一篇论文的一部分:

A closure is a function written by another function. Closures areso-called because they enclose the environment of the parentfunction, and can access all variables and parameters in thatfunction. This is useful because it allows us to have two levels ofparameters. One level of parameters (the parent) controls how thefunction works. The other level (the child) does the work. Thefollowing example shows how can use this idea to generate a family ofpower functions. The parent function (power) creates child functions(square and cube) that actually do the hard work.

power <- function(exponent) {
function(x) x ^ exponent
}

square <- power(2)
square(2) # -> [1] 4
square(4) # -> [1] 16

cube <- power(3)
cube(2) # -> [1] 8
cube(4) # -> [1] 64

在两个级别管理变量的能力还可以通过允许函数修改其父环境中的变量来维护跨函数调用的状态。管理不同级别变量的关键是双箭头赋值运算符<<- 。与始终在当前级别起作用的通常单箭头赋值( <- )不同,双箭头运算符可以修改父级别中的变量。

这使得可以维护一个记录函数被调用次数的计数器,如以下示例所示。每次new_counter运行时,它创建一个环境,初始化计数器 i在此环境中,然后创建一个新函数。

new_counter <- function() {
i <- 0
function() {
# do something useful, then ...
i <<- i + 1
i
}
}

新函数是一个闭包,它的环境是封闭环境。什么时候倒闭counter_onecounter_two运行时,每个都会修改其封闭环境中的计数器,然后返回当前计数。

counter_one <- new_counter()
counter_two <- new_counter()

counter_one() # -> [1] 1
counter_one() # -> [1] 2
counter_two() # -> [1] 1

关于r - 如何在 R 中使用 "<<-"(范围分配)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2628621/

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