In R, I want to call apply on a huge data.frame, and write values back into specific positions of other dataframes.
However, using '<<-' only works when I call the apply function from the global environment. As I understand, '<<-' searches the parent.env() for the variable. Why is the parent environment of the function called in bar() not bar's environment? Thanks!
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