Tabulate coefficients from lm

后端 未结 5 1621
失恋的感觉
失恋的感觉 2021-01-25 17:32

I have 10 linear models where I only need some information, namely: r-squared, p-value, coefficients of slope and intercept. I managed to extract these values (via ridiculously

5条回答
  •  星月不相逢
    2021-01-25 18:06

    Here is a base R solution:

    data <- read.csv("./data/so53933238.csv",header=TRUE)
    
    # split by value of CatChro into a list of datasets
    dataList <- split(data,data$CatChro)
    
    # process the list with lm(), extract results to a data frame, write to a list
    lmResults <- lapply(dataList,function(x){
         y <- summary(lm(Qend ~ Rainfall,data = x))
         Intercept <- y$coefficients[1,1]
         Slope <- y$coefficients[2,1]
         rSquared <- y$r.squared
         adjRSquared <- y$adj.r.squared
         f <- y$fstatistic[1]
         pValue <- pf(y$fstatistic[1],y$fstatistic[2],y$fstatistic[3],lower.tail = FALSE)
         data.frame(Slope,Intercept,rSquared,adjRSquared,pValue)
    })
    lmResultTable <- do.call(rbind,lmResults)
    # add CatChro indicators
    lmResultTable$catChro <- names(dataList)
    
    lmResultTable 
    

    ...and the output:

        > lmResultTable
                Slope   Intercept   rSquared  adjRSquared       pValue catChro
    A3D1 0.0004085644 0.011876543 0.28069553  0.254054622 0.0031181110    A3D1
    A3D2 0.0005431693 0.023601325 0.03384173  0.005425311 0.2828170556    A3D2
    A3D3 0.0001451185 0.022106960 0.04285322  0.002972105 0.3102578215    A3D3
    A3D4 0.0006614213 0.009301843 0.37219027  0.349768492 0.0003442445    A3D4
    A3D5 0.0001084626 0.014341399 0.04411669 -0.008987936 0.3741011769    A3D5
    A3G1 0.0001147645 0.024432020 0.03627553  0.011564648 0.2329519751    A3G1
    A3G2 0.0004583538 0.026079409 0.06449971  0.041112205 0.1045970987    A3G2
    A3G3 0.0006964512 0.043537869 0.07587433  0.054383038 0.0670399684    A3G3
    A3G4 0.0006442175 0.023706652 0.17337420  0.155404076 0.0032431299    A3G4
    A3G5 0.0006658466 0.025994831 0.17227383  0.150491566 0.0077413595    A3G5
    >
    

    To render the output in a tabular format in HTML, one can use knitr::kable().

    library(knitr)
    kable(lmResultTable[1:5],row.names=TRUE,digits=5) 
    

    ...which produces the following output after rendering the Markdown:

提交回复
热议问题