Search code examples
rdplyrregressiontidyversestata

R equivalent of Stata * in regression


I am looking for an equivalent in R of Stata's * function that I can use when running regressions.

For example, if I have a dataframe like the following:

outcome  var1  var2  var3  new
  3        2     3     4    3
  2        3     2     4    2
  4        3     2     1    4

I would like to be able to select all variable names that begin with "var" without typing each one out separately in order to run the following regression more efficiently:

lm(outcome ~ var1 + var2 + var3 + new, data = df)

This question explains how I can select the necessary columns. How can I cleanly incorporate these into a regression?


Solution

  • One technique is to subset the data to the required columns, and then to use the . operator for the formula object to represent the independent variables in lm(). The . operator is interpreted as "all columns not otherwise in the formula".

    data <- as.data.frame(matrix(runif(1000),nrow = 100)*100)
    colnames(data) <- c("outcome", "x1","x2","x3","x4", "x5","x6", "x7", "var8", "var9")
    
    # select outcome plus vars beginning with var
    desiredCols <- grepl("var",colnames(data)) | grepl("outcome",colnames(data))
    
    # use desiredCols to subset data frame argument in lm()
    summary(lm(outcome ~ .,data = data[desiredCols]))
    

    ...and the output:

    > summary(lm(outcome ~ .,data = data[desiredCols]))
    
    Call:
    lm(formula = outcome ~ ., data = data[desiredCols])
    
    Residuals:
        Min      1Q  Median      3Q     Max 
    -57.902 -25.359   2.296  26.213  52.871 
    
    Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
    (Intercept) 58.712722   7.334937   8.005 2.62e-12 ***
    var8         0.008617   0.101298   0.085    0.932    
    var9        -0.154073   0.103438  -1.490    0.140    
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    Residual standard error: 29.86 on 97 degrees of freedom
    Multiple R-squared:  0.02249,   Adjusted R-squared:  0.002331 
    F-statistic: 1.116 on 2 and 97 DF,  p-value: 0.3319
    
    >