0

I need to calculate β^0 and β^1 for a simple linear regression yi = β0 + β1xi with 87% confidence intervals for β0 and β1 and have to display my results with three significant digits in the following format:

      Est    L    U
beta0 1.13 0.889 1.37
beta1 3.57 1.950 5.19

What code should I use to get it in this format?

I have done the following, but cannot figure out how to show Intercept and x as beta0 and beta1 with their Estimate and Lower CI and Upper CI:

> M <- lm(y ~ x) # fit linear model
> signif(coef(M), digits = 2) # MLE's of beta
(Intercept)           x 
      -5.40        0.13 
> 
> signif(confint(M, level = 0.87), digits = 3)
             6.5 % 93.5 %
(Intercept) -5.710 -5.160
x            0.127  0.136

I'm doing this in RStudio

EDIT: I've used data.frame to get it like this:

> # data.frame for MLE's of beta with 87% confidence interval for beta0 and beta1
> data.frame(df, stringsAsFactors = )
        Est      L      U
beta0 -5.40 -5.710 -5.160
beta1  0.13  0.127  0.136
> Est <- c(-5.40, 0.13)
> L <- c(-5.710, 0.127)
> U <- c(-5.160, 0.136)
> df <- data.frame(Est,L,U)
> row.names(df) <- c('beta0', 'beta1')

But is there a better way of getting it in this form using the built-in R functions lm, coef, confint?

CC25
  • 15
  • 4

1 Answers1

0

Rename the rownames and colnames of the output of confint.

n <- 50
df <- data.frame(x = rnorm(n), y = rnorm(n))
fit <- lm(y ~ x, data = df)
ci <- confint(fit, level = .87)
colnames(ci) <- c("L", "U")
rownames(ci) <- c("beta0", "beta1")

ci
               L           U
beta0 -0.4962463 0.002210674
beta1 -0.3157171 0.152844873

If you need the estimate as an additional row, convert the ci matrix to a dataframe and add fit$coefficients as an additional column:

ci_df <- data.frame(ci)
est <- fit$coefficients
ci_df$Est <- est

ci_df
               L           U         Est
beta0 -0.4962463 0.002210674 -0.24701781
beta1 -0.3157171 0.152844873 -0.08143609

And if you need to round, just do round(ci_df, 3).

andrew_reece
  • 20,390
  • 3
  • 33
  • 58
  • How do I make Est the first column? – CC25 Feb 04 '20 at 05:14
  • There are a ton of SO posts on changing column order in a df. I see that you are a new contributor, so a word of advice: asking a simple question like this when googling "how to rearrange columns in a data frame in r" yields many easy answers, suggests you're not doing much work to find your own answers. That impression often isn't well-received on this site, as people generally like to feel like everyone's making an honest effort to learn. Here's a good link to get you pointed in the right direction: https://stackoverflow.com/questions/5620885/how-does-one-reorder-columns-in-a-data-frame – andrew_reece Feb 04 '20 at 05:20
  • 1
    Thanks a lot for your help I actually managed to figure it out from the code – CC25 Feb 04 '20 at 05:30