Assign variables to the apply () - d function using << -

In R, I want to call the application on a huge data.frame and write the values ​​back to certain positions of other data frames.

However, using '<<-' only works when calling the apply function from the global environment. As I understand it, '<<- - is looking for parent.env () for the variable. Why is the parent environment of the function called in bar () not surrounded by the environment? Thank!

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
+3
source share
2 answers

Since I'm inside the package namespace, I have to use another solution for Etiennebr. And I think it's pretty elegant: setting the environment 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()
+2
source

, R ( ), global.env foo.

bar <- function() {
    foo <<-1:10
    apply(data.frame(a=1:10),1,do_write_foo)
    foo
}
bar()
# [1] 101 102 103 104 105 106 107 108 109 110
+1

Source: https://habr.com/ru/post/1758719/


All Articles