R : Pass argument to glm inside an R function
Solution with substitute (@DWin suggestion).
function(y, x, dataset, weights){
f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
logLik(eval(f))
}
How to pass function arguments to R model object
Try this:
grid = (cbind(c('wl', 'livingd', 'deceasedt'), c('wl_time', 'ld_time', 'dec_time')))
for (k in 1:nrow(grid)){
f=function(y=as.name(grid[k,1]), offset=as.name(grid[k,2])){
m=glm(get(y)~chain_class2+sex_new+age_cat+race_new,
family=poisson(link='log'),
data=poissonset,
offset=log(get(offset)/12))
}
}
R - how to pass formula to a with(df, glm(y ~ x)) construction inside a function
Try wrapping the formula in as.formula
fit_model_mi = function(formula) {
with(mtcars.imp, glm(as.formula(formula)) )
}
Seems to work:
> fit_model_mi("mpg ~ cyl")
call :
with.mids(data = mtcars.imp, expr = glm(as.formula(formula)))
call1 :
mice(data = mtcars, m = 5)
nmis :
mpg cyl disp hp drat wt qsec vs am gear carb
0 0 0 0 1 0 0 0 0 0 0
analyses :
[[1]]
Call: glm(formula = as.formula(formula))
Coefficients:
(Intercept) cyl
37.885 -2.876
Degrees of Freedom: 31 Total (i.e. Null); 30 Residual
Null Deviance: 1126
Residual Deviance: 308.3 AIC: 169.3
pass family= to step() via glm() programmatically
I think the following solution, based on eval
, bquote
and .()
might solve your problem.
I also have R-version 3.2.4 installed, and I got the exact same error you got from your code. The solution below made it work at my computer.
getCoef <- function(formula,
family = c("gaussian", "binomial"),
data){
model_fam <- match.arg(family, c("gaussian", "binomial"))
fit_null <- eval(bquote(
glm(update(.(formula),".~1"),
family = .(model_fam),
data = .(data))))
message("So far so good")
fit_stepBIC <- step(fit_null,
formula,
direction="forward",
k = log(nrow(data)),
trace=0)
message("Doesn't make it this far")
fit_stepBIC$coefficients
}
# returns error 'model_fam' not found
getCoef(formula = Petal.Length ~ Petal.Width + Species,
family = "gaussian",
data = iris)
So far so good
Doesn't make it this far
(Intercept) Speciesversicolor Speciesvirginica Petal.Width
1.211397 1.697791 2.276693 1.018712
Passing Argument to lm in R within Function
Building on the comments, gear
isn't defined globally. It works inside the stand-alone lm
call as you specify the data you are using, so lm
knows to take gear
from df
.
Howver, gear
itself doesn't exist outside that stand-alone lm
function. This is shown by the output of gear
> gear
Error: object 'gear' not found
You can pass the gear
into the function using df$gear
weightvar <- df$gear
ols <- olswrapper(mpg ~ cyl + qsec, weightvar , df = df)
Passing weights to glm() using rlang
The issue is that glm()
can recognize an expression being provided to its weights
argument, but doesn't support quasiquotation, because it uses the base quote()
/ substitute()
/ eval()
mechanisms instead of rlang
. This causes problems for nested expression arithmetic.
One way to get around it is to compose the entire glm
expression, then evaluate it. You can use ...
to supply optional arguments.
myglm2 <- function( .data, y, x, weights, ... ) {
myglm <- expr( glm(!!enexpr(y) ~ !!enexpr(x), data=.data,
weights = !!enexpr(weights), ...) )
eval(myglm)
}
myglm2(mydata, outcome, group)
# Call: glm(formula = outcome ~ group, data = .data)
myglm2(mydata, outcome, group, wgts)
# Call: glm(formula = outcome ~ group, data = .data, weights = wgts)
myglm2(mydata, outcome, group, wgts, subset=7:10)
# Call: glm(formula = outcome ~ group, data = .data, weights = wgts,
# subset = ..1)
# While masked as ..1, the 7:10 is nevertheless correctly passed to glm()
To follow @lionel's suggestion, you can encapsulate the expression composition / evaluation into a standalone function:
value <- function( e ) {eval(enexpr(e), caller_env())}
myglm2 <- function( .data, y, x, weights, ... ) {
value( glm(!!enexpr(y) ~ !!enexpr(x), data=.data,
weights = !!enexpr(weights), ...) )
}
How to make glm object within a function take input variable names and not parameter names?
You can use the as.formula()
function to transform a string with your formula before calling glm()
. This will solve your question (How do I make the glm objects refer to actual variables), but I'm not sure if it is enough for the calling cv.glm
later (I couldn't reproduce your code here, without errors). To be clear, you replace the line
mod = glm(dep~poly(indep,i),data=dat)
with something like:
myexp = paste0(dep, "~ poly(", indep, ",", i, ")")
mod = glm(as.formula(myexp), data=dat)
it's required then to make the variables dep
and indep
to be characters with names of the variables that you want to refer to (e.g. indep="displ"
).
How to pass bunch of elements as an argument in R?
The reformulate()
function is what you need!
mylabels = c("Lag1","Lag2","Lag3","Lag4")
myresponse = "Direction"
reformulate(mylabels, myresponse)
Direction ~ Lag1 + Lag2 + Lag3 + Lag4
Related Topics
Datalabels in R Highcharter Cannot Be Seen After Print as Png or Jpg
Determine the Number of Na Values in a Column
What Does the R Function 'Poly' Really Do
Replacement for "Rename" in Dplyr
Use Pipe Operator %>% with Replacement Functions Like Colnames()<-
How to Align Multiple Ggplot2 Plots and Add Shadows Over All of Them
Plotting Multiple Time Series on the Same Plot Using Ggplot()
Reset Par to the Default Values at Startup
Documenttermmatrix Error on Corpus Argument
How to Set Legend Alpha with Ggplot2
Changing Font in PDF Produced by Rmarkdown
Count Number of Records and Generate Row Number Within Each Group in a Data.Table
Create a Dynamic Table on Shiny App Based on Shiny Widget and Row Selection of Another Datatable
Save Imported CSV Data in Vector - R
Ggplot X-Axis Labels with All X-Axis Values