R: Regress all variables that match certain pattern

前端 未结 2 644
盖世英雄少女心
盖世英雄少女心 2021-01-21 15:56

Is there a way in R to add all variables into a regression that match a certain pattern? For example, I have a bunch of variables in my dataset that correspond to holidays with

2条回答
  •  -上瘾入骨i
    2021-01-21 16:49

    To programmatically construct a formula, have a look at reformulate().

    Here's an example that uses grep() to find all variables that begin with a "d" and then uses reformulate() to plug them in as the regressor variables on the RHS of a formula object.

    vv <- grep("^d.*", names(mtcars), value=TRUE)
    ff <- reformulate(termlabels=vv, response="mpg")
    lm(ff, data=mtcars)
    # 
    # Call:
    # lm(formula = ff, data = mtcars)
    # 
    # Coefficients:
    # (Intercept)         disp         drat  
    #    21.84488     -0.03569      1.80203  
    

提交回复
热议问题