这是我先前提出的问题中的一个功能:How to let R predict user input 我想使向xname参数提供几个名称变得更容易,但是我仍然无法为该做些什么。
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)
}
这就是我尝试过的
vals<-names(mtcars)[-1]
lmfun(mtcars,mpg,disp)#This works
我怎样才能最好地完成这项工作?我尝试了其他几种方法,但只显示了这一点:
for(name in 1:seq_along(vals)){
name<-eval(substitute(name))
lmfun(mtcars,mpg,name)
}
此操作失败:
deparse(substitute(xname))中的错误: “ arg”应为“ mpg”,“ cyl”,“ disp”,“ hp”,“ drat”,“ wt”,“ qsec”,“ vs”,“ am”,“ gear”,“ carb”之一
也尝试过:
for(name in 1:length(vals)){
vals<-noquote(vals)
lmfun(mtcars,mpg,vals[name])
}
如果我能指出整合多线性回归的方法,我也将不胜感激。那就是xname+xname1+xname2
谢谢!
答案 0 :(得分:1)
像这样使用lmfun
调用do.call
:
lapply(vals, function(val) do.call("lmfun", list(mtcars, quote(mpg), as.name(val))))
这也是可行的,尽管在可能的情况下通常首选不使用eval
的代码:
lapply(vals,
function(val) eval(substitute(lmfun(mtcars, mpg, val), list(val = as.name(val)))))
答案 1 :(得分:1)
可以在lm()
中轻松地完成多个单变量finalfit
。它喜欢正确指定的因素:
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)
finalfit.org此处的文档中有很多选项。