简体   繁体   中英

Remove coefficients from lm output in R

I would like to remove all of the as.factor elements from the output of an ordinary least squares lm() model in R. The last line doesn't work, but for example:

frame <- data.frame(y = rnorm(100), x= rnorm(100), block = sample(c("A", "B", "C", "D"), 100, replace = TRUE))
mod <- lm(y ~ x + as.factor(block), data = frame)
summary(mod)

summary(mod)$coefficients[3:5,] <- NULL

Is there a way to remove all of these elements so that the saved `lm' object no longer has them? Thanks.

One option is to use felm function in lfe package.

As stated in the package:

The package is intended for linear models with multiple group fixed effects, ie with 2 or more factors with a large number of levels. It performs similar functions as lm , but it uses a special method for projecting out multiple group fixed effects from the normal equations, hence it is faster.

set.seed(123)
frame <- data.frame(y = rnorm(100), x= rnorm(100), block = sample(c("A", "B", "C", "D"), 100, replace = TRUE))
id<-as.factor(frame$block)
mod <- lm(y ~ x + id, data = frame) #lm
summary(mod)
Call:
lm(formula = y ~ x + id, data = frame)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.53394 -0.68372  0.04072  0.67805  2.00777 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)  
(Intercept)  0.18115    0.17201   1.053   0.2950  
x           -0.08310    0.09604  -0.865   0.3891  
idB          0.04834    0.24645   0.196   0.8449  
idC         -0.51265    0.25052  -2.046   0.0435 *
idD          0.04905    0.26073   0.188   0.8512  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.9002 on 95 degrees of freedom
Multiple R-squared:  0.06677,   Adjusted R-squared:  0.02747 
F-statistic: 1.699 on 4 and 95 DF,  p-value: 0.1566


library(lfe)
est <- felm(y ~ x| id)
summary(est)

Call:
   felm(formula = y ~ x | id, data = frame) 

Residuals:
     Min       1Q   Median       3Q      Max 
-2.53394 -0.68372  0.04072  0.67805  2.00777 

Coefficients:
  Estimate Std. Error t value Pr(>|t|)
x -0.08310    0.09604  -0.865    0.389

Residual standard error: 0.9002 on 95 degrees of freedom
Multiple R-squared(full model): 0.06677   Adjusted R-squared: 0.02747 
Multiple R-squared(proj model): 0.00782   Adjusted R-squared: -0.03396 
F-statistic(full model):1.699 on 4 and 95 DF, p-value: 0.1566 
F-statistic(proj model): 0.7487 on 1 and 95 DF, p-value: 0.3891 

PS A similar program for Stata is reghdfe .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM