R 相当于 Stata * 在回归中

R equivalent of Stata * in regression

我正在寻找 R 中 Stata * 函数的等价物,我可以在 运行ning 回归时使用它。

例如,如果我有如下数据框:

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

我希望能够 select 所有以 "var" 开头的变量名称,而无需单独输入每个变量名称,以便更有效地 运行 以下回归:

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

解释了我如何 select 必要的列。我如何才能将这些干净地合并到回归中?

一种技术是将数据子集化为所需的列,然后对formula 对象使用. 运算符来表示lm() 中的自变量。 . 运算符被解释为 "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]))

...输出:

> 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

>