Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

stata - How do I create a "macro" for regressors in R?

For long and repeating models I want to create a "macro" (so called in Stata and there accomplished with global var1 var2 ...) which contains the regressors of the model formula.

For example from

library(car)
lm(income ~ education + prestige, data = Duncan)

I want something like:

regressors <- c("education", "prestige")
lm(income ~ @regressors, data = Duncan)  

I could find is this approach. But my application on the regressors won't work:

reg = lm(income ~ bquote(y ~ .(regressors)), data = Duncan)

as it throws me:

Error in model.frame.default(formula = y ~ bquote(.y ~ (regressors)), data =
Duncan,  :  invalid type (language) for variable 'bquote(.y ~ (regressors))'

Even the accepted answer of same question:

lm(formula(paste('var ~ ', regressors)), data = Duncan)

strikes and shows me:

Error in model.frame.default(formula = formula(paste("var ~ ", regressors)),
: object is not a matrix`. 

And of course I tried as.matrix(regressors) :)

So, what else can I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the scenario you described, where regressors is in the global environment, you could use:

lm(as.formula(paste("income~", paste(regressors, collapse="+"))), data = 
Duncan)

Alternatively, you could use a function:

modincome <- function(regressors){
    lm(as.formula(paste("income~", paste(regressors, collapse="+"))), data = 
Duncan)  
}

modincome(c("education", "prestige"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...