在R中,我想在一个巨大的data.frame上调用apply,然后将值写回到其他dataframe的特定位置。
但是,仅当我从全局环境调用apply函数时,才使用'<谢谢!
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/