Exporting R lm regression with cbind to text

江枫思渺然 提交于 2019-12-02 01:59:39

I've found tidy in the broom package useful for this:

fit <- lm(y ~ x, data.frame(x=1:10, y=rnorm(10))) # dummy example

library(broom)
tidy(fit)

# result is a data.frame:
#         term   estimate std.error  statistic   p.value
#1 (Intercept) -0.3317979 1.2034887 -0.2756967 0.7897685
#2           x -0.0663678 0.1939598 -0.3421730 0.7410364
x=1:100
y=2*x+1
fit<-lm(y~x)

Use the str(summary(fit)) you will see the structure of summary,and there is something that cannot be converted to dataframe

> str(summary(fit))
List of 11
 $ call         : language lm(formula = y ~ x)
 $ terms        :Classes 'terms', 'formula' length 3 y ~ x
  .. ..- attr(*, "variables")= language list(y, x)
  .. ..- attr(*, "factors")= int [1:2, 1] 0 1
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:2] "y" "x"
  .. .. .. ..$ : chr "x"
  .. ..- attr(*, "term.labels")= chr "x"
  .. ..- attr(*, "order")= int 1
  .. ..- attr(*, "intercept")= int 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
  .. ..- attr(*, "predvars")= language list(y, x)
  .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
  .. .. ..- attr(*, "names")= chr [1:2] "y" "x"
 $ residuals    : Named num [1:100] 7.15e-14 -5.36e-13 2.16e-14 9.05e-15 2.49e-14 ...
  ..- attr(*, "names")= chr [1:100] "1" "2" "3" "4" ...
 $ coefficients : num [1:2, 1:4] 1.00 2.00 1.12e-14 1.92e-16 8.93e+13 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "(Intercept)" "x"
  .. ..$ : chr [1:4] "Estimate" "Std. Error" "t value" "Pr(>|t|)"
 $ aliased      : Named logi [1:2] FALSE FALSE
  ..- attr(*, "names")= chr [1:2] "(Intercept)" "x"
 $ sigma        : num 5.56e-14
 $ df           : int [1:3] 2 98 2
 $ r.squared    : num 1
 $ adj.r.squared: num 1
 $ fstatistic   : Named num [1:3] 1.08e+32 1.00 9.80e+01
  ..- attr(*, "names")= chr [1:3] "value" "numdf" "dendf"
 $ cov.unscaled : num [1:2, 1:2] 0.040606 -0.000606 -0.000606 0.000012
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "(Intercept)" "x"
  .. ..$ : chr [1:2] "(Intercept)" "x"
 - attr(*, "class")= chr "summary.lm"

So use this can get the t-statistics and standard errors

write.csv(summary(fit)$coefficients,'C:/Users/sony/Desktop/a.csv')

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!