Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 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 Answer

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...