Once again: setting up the environment inside the function

There are already many discussions about the area, environments, and functions. See here or here . However, I'm not sure I found a good solution to the following problem:

 df <- data.frame(id=rep(LETTERS[1:2],each=2), x=1:4)
 d <- -1
 myfun <- function(df, d){
          require(plyr)
          new.dat <- ddply(df, .(id), transform, x=x*d) 
          return(new.dat)}
 myfun(df, 1)

You can easily verify that the globally defined was used d=-1, and not d=1as indicated in the argument. (If not globally defined d, a message is returned object not found). Now the big question is: how do I make the argument of the dfunction used, and not globally defined d?

I got the impression that the following should work:

      myfun2 <- function(df, d){
          here <- environment()
          new.dat <- ddply(df, .(id), transform, x=x*with(here,d)) 
          return(new.dat)}
      myfun2(df, 1)

As far as I understand, it with(here, d)extracts an object dfrom the environment here. So, the result should be 1. The error returns, however, by saying

  Error in eval(substitute(expr), data, enclos = parent.frame()) : 
   invalid 'envir' argument of type 'closure' 

, , , , - , . , ddply - with(...) .

, , attach :

 myfun3 <- function(df, d){
   here <- environment()
   attach(here)
   new.dat <- ddply(df, .(id), transform, x=x*d) 
   detach(here)
   return(new.dat)
 }

, , d d, , , .

/ .

+4
1

, d, force. :

d <- force(d)

myfun.


, , . , ddply df , d, force . , transform insdie here.

myfun <- function(df, d){
      require(plyr)
      new.dat <- ddply(df, .(id), here(transform), x=x*d) 
      return(new.dat)}

:
, require FALSE, library.
mutate transform.
return.

myfun <- function(df, d){
      library(plyr)
      ddply(df, .(id), here(mutate), x=x*d)}
+4

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


All Articles