gpt4 book ai didi

r - 使用 <<- 在 apply()-d 函数中分配变量

转载 作者:行者123 更新时间:2023-12-02 14:21:05 25 4
gpt4 key购买 nike

在 R 中,我想在一个巨大的 data.frame 上调用 apply,并将值写回到其他 dataframe 的特定位置。

但是,仅当我从全局环境调用 apply 函数时,使用“<<-”才有效。据我了解,“<<-”在parent.env()中搜索变量。为什么bar()中调用的函数的父环境不是bar的环境?谢谢!

do_write_foo1 <- function(x) {
cat("parent environment of function called in bar(): ")
print(parent.env(environment()))
foo1[x['a']] <<- 100+x['a']
}
do_write_foo2 <- function(x) {
foo2[x['a']] <<- 100+x['a']
}

bar <- function() {
cat("bar environment: ")
print(environment())
foo1 <- 1:10
apply(data.frame(a=1:10),1,do_write_foo1)
foo1
}

# this does not work:
bar()
# bar environment: <environment: 0x3bb6278>
# parent environment of function called in bar(): <environment: R_GlobalEnv>
# Error in foo1[x["a"]] <<- 100 + x["a"] : object 'foo1' not found


# this works:
foo2<-1:10
apply(data.frame(a=1:10),1,do_write_foo2)
foo2
# [1] 101 102 103 104 105 106 107 108 109 110

最佳答案

由于我位于包命名空间内,因此我必须使用与 Etiennebr 不同的解决方案。我认为这相当优雅:将 bar 的环境分配给 do_write_foo1。

do_write_foo1 <- function(x) {
cat("parent environment of function called in bar(): ")
print(parent.env(environment()))
foo1[x['a']] <<- 100+x['a']
}

bar <- function() {
cat("bar environment: ")
print(environment())
foo1 <- 1:10
environment(do_write_foo1) <- environment()
apply(data.frame(a=1:10),1,do_write_foo1)
foo1
}

# now it works:
bar()

关于r - 使用 <<- 在 apply()-d 函数中分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3439894/

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