Reputation: 13319
This is a function from an earlier question of mine: How to let R predict user input I would like to make it easier to supply several names to the xname argument but I still can't fugure out just how to do that.
lmfun<-function(df,yname,xname){
y<-deparse(substitute(yname))
x<-deparse(substitute(xname))
f<-as.formula(paste0(y,"~",x))
lm.fit<-do.call("lm",list(data=quote(df),f))
coef(lm.fit)
}
Here's what I've tried
vals<-names(mtcars)[-1]
lmfun(mtcars,mpg,disp)#This works
How can I best make this work? I've tried several other ways but showing only this:
for(name in 1:seq_along(vals)){
name<-eval(substitute(name))
lmfun(mtcars,mpg,name)
}
This fails:
Error in deparse(substitute(xname)) : 'arg' should be one of “mpg”, “cyl”, “disp”, “hp”, “drat”, “wt”, “qsec”, “vs”, “am”, “gear”, “carb”
Also tried:
for(name in 1:length(vals)){
vals<-noquote(vals)
lmfun(mtcars,mpg,vals[name])
}
I would also appreciate if I could be pointed at a way to incorporate multilinear regression. That is xname+xname1+xname2
Thanks!
Upvotes: 0
Views: 89
Reputation: 1381
Multiple univariable lm()
can be easily done in finalfit
. It likes factors specified correctly:
library(finalfit)
dependent = "mpg"
explanatory = names(mtcars)[-1]
mtcars %>%
dplyr::mutate(
cyl = factor(cyl),
vs = factor(vs),
am = factor(am),
gear = factor(gear)
) %>%
finalfit(dependent, explanatory)
Dependent: mpg Mean (sd) Coefficient (univariable) Coefficient (multivariable)
cyl 4 26.7 (4.5) - -
6 19.7 (1.5) -6.92 (-10.11 to -3.73, p<0.001) -1.20 (-6.20 to 3.80, p=0.621)
8 15.1 (2.6) -11.56 (-14.22 to -8.91, p<0.001) 3.05 (-7.05 to 13.16, p=0.535)
disp [71.1,472] 20.1 (6.0) -0.04 (-0.05 to -0.03, p<0.001) 0.01 (-0.02 to 0.05, p=0.487)
hp [52,335] 20.1 (6.0) -0.07 (-0.09 to -0.05, p<0.001) -0.06 (-0.12 to 0.01, p=0.088)
drat [2.76,4.93] 20.1 (6.0) 7.68 (4.60 to 10.76, p<0.001) 0.74 (-3.42 to 4.89, p=0.715)
wt [1.51,5.42] 20.1 (6.0) -5.34 (-6.49 to -4.20, p<0.001) -3.55 (-7.54 to 0.45, p=0.079)
qsec [14.5,22.9] 20.1 (6.0) 1.41 (0.27 to 2.55, p=0.017) 0.77 (-0.81 to 2.34, p=0.320)
vs 0 16.6 (3.9) - -
1 24.6 (5.4) 7.94 (4.61 to 11.27, p<0.001) 2.49 (-2.83 to 7.81, p=0.340)
am 0 17.1 (3.8) - -
1 24.4 (6.2) 7.24 (3.64 to 10.85, p<0.001) 3.35 (-1.44 to 8.14, p=0.160)
gear 3 16.1 (3.4) - -
4 24.5 (5.3) 8.43 (4.70 to 12.16, p<0.001) -1.00 (-7.17 to 5.17, p=0.738)
5 21.4 (6.7) 5.27 (0.30 to 10.25, p=0.038) 1.06 (-5.27 to 7.40, p=0.729)
carb [1,8] 20.1 (6.0) -2.06 (-3.22 to -0.89, p=0.001) 0.79 (-1.38 to 2.96, p=0.457)
Lots of options in the documentation here finalfit.org.
Upvotes: 1
Reputation: 269501
Invoke lmfun
using do.call
like this:
lapply(vals, function(val) do.call("lmfun", list(mtcars, quote(mpg), as.name(val))))
This also works although generally code which does not use eval
is preferred when possible:
lapply(vals,
function(val) eval(substitute(lmfun(mtcars, mpg, val), list(val = as.name(val)))))
Upvotes: 1