R: Regress all variables that match certain pattern

前端 未结 2 643
盖世英雄少女心
盖世英雄少女心 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条回答
  • 2021-01-21 16:45

    A string can be turned into a formula.

    data(iris)
    
    fmla <- as.formula(paste("Species ~", 
                   paste(grep("Width", names(iris), value = TRUE), collapse = " + ")))
    
    glm(fmla, data = iris, family = binomial(link = "logit"))
    
    0 讨论(0)
  • 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  
    
    0 讨论(0)
提交回复
热议问题