Hi, I am trying to call a second function lsmeans() within my user-defined function. Although the first one with just glm() works, the second one with lsmeans() does not.
@raytong and @ technocrat or could anyone help?
set.seed(234)
sex <- sample(c("M", "F"), size=100, replace=TRUE)
age <- rnorm(n=100, mean=20 + 4*(sex=="F"), sd=0.1)
dsn <- data.frame(sex, age)
rm(sex, age) #remove sex and age from the global environment for reproducibility
to_analyze <- function(dep, indep, data){
glm(substitute(dep ~ factor(indep)), data=data)
}
to_analyze(dep=age, indep=sex, data=dsn)
#>
#> Call: glm(formula = substitute(dep ~ factor(indep)), data = data)
#>
#> Coefficients:
#> (Intercept) factor(sex)M
#> 24.006 -4.034
#>
#> Degrees of Freedom: 99 Total (i.e. Null); 98 Residual
#> Null Deviance: 397.3
#> Residual Deviance: 0.8152 AIC: -191.2
However, I am stuck again because I am trying the call the output from this model in lsmeans::lsmeans()
to predict marginal means and return the output but it is giving me an error. Any help would be greatly appreciated
to_predict_lsmeans <- function(dep, indep, data){
model <- glm(substitute(dep ~ factor(indep)), data=data)
pred <- lsmeans::lsmeans(model, substitute(~ factor(indep)), offset=substitute(data)$log(age), type ="response" )
return(pred)
}
pred <- to_predict_lsmeans(dep=age, indep=sex, data=dsn)
#> Error in ref_grid(object, ...): We are unable to reconstruct the data.
#> The variables needed are:
#> sex
#> Are any of these actually constants? (specify via 'params = ')
#> The dataset name is:
#> data
#> Does the data still exist? Or you can specify a dataset via 'data = '
pred
#> Error in eval(expr, envir, enclos): object 'pred' not found