How to run a graph of the effect inside the function R

Update: The previous name was Is there any specific way to pass data frame as an argument to a function?, but it was the wrong question according to the brilliant guys here. Original mail is below.

When I executed the following function with somefunc(sleepstudy),

somefunc<-function (dataLme) 
{
 library(effects)
 library(lme4)

 fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), dataLme,
      REML = 0, verbose = TRUE)

 plot(effect("Days",fm8))
}

I got an error.

Error in plot(effect("Days", fm8)) : 
  error in evaluating the argument 'x' in selecting a method for function 'plot': Error in is.data.frame(data) : object 'dataLme' not found

But if I manually performed

library(effects)
library(lme4)
fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), sleepstudy,
    REML = 0, verbose = TRUE)
plot(effect("Days",fm8))

I have not received any errors.

I thought R was passing a value meaning copying the entire contents of the object into the argument of the function. But it seems like I'm not quite right. Can anyone explain what is happening?

+5
source share
2 answers

A (hacker) workaround is to assign it dataLmeto a global environment where it effect()can find it:

library(effects)
library(lme4)

somefunc <- function (dataLme) {
    ## Assign to a symbol that unlikely to be in use in .GlobalEnv
    ## (and make sure this function cleans up after itself!)
    assign(".TeMpVaR", dataLme, envir=globalenv())
    on.exit(rm(.TeMpVaR, envir=globalenv()))

    fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), .TeMpVaR,
         REML = 0, verbose = TRUE)    
    plot(effect("Days",fm8))
}

somefunc(sleepstudy)
+5
source

, . , effects, lme4 ( , : lme4, , lme4.0 ...)

library("effects")

showpkgs <- function() names(sessionInfo()$otherPkgs)
somefunc<-function (dataLme, pkg="nlme")  {
    require(pkg,character.only=TRUE)
    on.exit(detach(paste("package",pkg,sep=":"),unload=TRUE,character.only=TRUE))
    if (pkg=="nlme") {
        fm8 <- lme(Reaction ~ 1 + Days,random=~Days|Subject, dataLme)
    } else {
        fm8 <- lmer(Reaction ~ 1 + Days + (1 + Days|Subject), dataLme, REML = 0)
    }
    plot(effect("Days",fm8))
}

, lme4, development lme4 nlme

data("sleepstudy",package="lme4")
showpkgs()
somefunc(sleepstudy)  ## nlme
showpkgs()  ## warning about unloading nlme namespace due to glmmADMB dep. (??)
somefunc(sleepstudy,pkg="lme4.0")  ## lme4-stable
showpkgs()  ## failure to remove Matrix/warning message
somefunc(sleepstudy,pkg="lme4")    ## lme4-devel
showpkgs()  ## leaves RcppEigen, Rcpp loaded as well

effects, . eval(cl) eval(cl,envir=environment(formula(mod))) lme4, lme4 nlme...

+2

All Articles