R 将lm中的系数制成表格

R 将lm中的系数制成表格,r,extract,information-extraction,tabulate,R,Extract,Information Extraction,Tabulate,我有10个线性模型,其中我只需要一些信息,即:r平方,p值,斜率系数和截距。我通过荒谬地重复代码,成功地提取了这些值。现在,我需要将这些值信息列成表格;列出线性模型1-10结果的行。有人能帮我吗?我还有数百个线性模型要做。我相信一定有办法 代码: 这是我预期结果的结构: 有什么方法可以做到这一点吗?使用librarydata.table可以做到这一点 d <- fread("example.csv") d[, .( r2 = (fit <- summary(lm(

我有10个线性模型,其中我只需要一些信息,即:r平方,p值,斜率系数和截距。我通过荒谬地重复代码,成功地提取了这些值。现在,我需要将这些值信息列成表格;列出线性模型1-10结果的行。有人能帮我吗?我还有数百个线性模型要做。我相信一定有办法

代码:

这是我预期结果的结构:

有什么方法可以做到这一点吗?

使用librarydata.table可以做到这一点

d <- fread("example.csv")
d[, .(
  r2         = (fit <- summary(lm(Qend~Rainfall)))$r.squared,
  adj.r2     = fit$adj.r.squared,
  intercept  = fit$coefficients[1,1], 
  gradient   = fit$coefficients[2,1],
  p.value    = {p <- fit$fstatistic; pf(p[1], p[2], p[3], lower.tail=FALSE)}),
  by  = CatChro]

#    CatChro         r2       adj.r2   intercept     gradient      p.value
# 1:    A3G1 0.03627553  0.011564648 0.024432020 0.0001147645 0.2329519751
# 2:    A3D1 0.28069553  0.254054622 0.011876543 0.0004085644 0.0031181110
# 3:    A3G2 0.06449971  0.041112205 0.026079409 0.0004583538 0.1045970987
# 4:    A3D2 0.03384173  0.005425311 0.023601325 0.0005431693 0.2828170556
# 5:    A3G3 0.07587433  0.054383038 0.043537869 0.0006964512 0.0670399684
# 6:    A3D3 0.04285322  0.002972105 0.022106960 0.0001451185 0.3102578215
# 7:    A3G4 0.17337420  0.155404076 0.023706652 0.0006442175 0.0032431299
# 8:    A3D4 0.37219027  0.349768492 0.009301843 0.0006614213 0.0003442445
# 9:    A3G5 0.17227383  0.150491566 0.025994831 0.0006658466 0.0077413595
#10:    A3D5 0.04411669 -0.008987936 0.014341399 0.0001084626 0.3741011769
使用librarydata.table可以执行以下操作

d <- fread("example.csv")
d[, .(
  r2         = (fit <- summary(lm(Qend~Rainfall)))$r.squared,
  adj.r2     = fit$adj.r.squared,
  intercept  = fit$coefficients[1,1], 
  gradient   = fit$coefficients[2,1],
  p.value    = {p <- fit$fstatistic; pf(p[1], p[2], p[3], lower.tail=FALSE)}),
  by  = CatChro]

#    CatChro         r2       adj.r2   intercept     gradient      p.value
# 1:    A3G1 0.03627553  0.011564648 0.024432020 0.0001147645 0.2329519751
# 2:    A3D1 0.28069553  0.254054622 0.011876543 0.0004085644 0.0031181110
# 3:    A3G2 0.06449971  0.041112205 0.026079409 0.0004583538 0.1045970987
# 4:    A3D2 0.03384173  0.005425311 0.023601325 0.0005431693 0.2828170556
# 5:    A3G3 0.07587433  0.054383038 0.043537869 0.0006964512 0.0670399684
# 6:    A3D3 0.04285322  0.002972105 0.022106960 0.0001451185 0.3102578215
# 7:    A3G4 0.17337420  0.155404076 0.023706652 0.0006442175 0.0032431299
# 8:    A3D4 0.37219027  0.349768492 0.009301843 0.0006614213 0.0003442445
# 9:    A3G5 0.17227383  0.150491566 0.025994831 0.0006658466 0.0077413595
#10:    A3D5 0.04411669 -0.008987936 0.014341399 0.0001084626 0.3741011769

考虑建立一个lm结果矩阵。首先创建一个定义的函数来处理带有结果提取的通用数据帧模型构建。然后,调用它,通过它可以按一个因子列对数据帧进行子集,并将每个子集传递给定义的方法。最后,rbind将所有分组矩阵合并为一个奇异输出

lm_results <- function(df) {

  model <- lm(Qend ~ Rainfall, data = df)
  res <- summary(model)

  p <- res$fstatistic

  c(gradient = res$coefficients[2,1],
    intercept = res$coefficients[2,2],
    r_sq = res$r.squared,
    adj_r_sq = res$adj.r.squared,
    f_stat = p[['value']],
    p_value = unname(pf(p[1], p[2], p[3], lower.tail=FALSE))
  )
}

matrix_list <- by(d, d$group, lm_results)

final_matrix <- do.call(rbind, matrix_list)
在随机种子数据上演示

set.seed(12262018)
data_tools <- c("sas", "stata", "spss", "python", "r", "julia")

d <- data.frame(
  group = sample(data_tools, 500, replace=TRUE),
  int = sample(1:15, 500, replace=TRUE),
  Qend = rnorm(500) / 100,
  Rainfall = rnorm(500) * 10
)
结果


考虑建立一个lm结果矩阵。首先创建一个定义的函数来处理带有结果提取的通用数据帧模型构建。然后,调用它,通过它可以按一个因子列对数据帧进行子集,并将每个子集传递给定义的方法。最后,rbind将所有分组矩阵合并为一个奇异输出

lm_results <- function(df) {

  model <- lm(Qend ~ Rainfall, data = df)
  res <- summary(model)

  p <- res$fstatistic

  c(gradient = res$coefficients[2,1],
    intercept = res$coefficients[2,2],
    r_sq = res$r.squared,
    adj_r_sq = res$adj.r.squared,
    f_stat = p[['value']],
    p_value = unname(pf(p[1], p[2], p[3], lower.tail=FALSE))
  )
}

matrix_list <- by(d, d$group, lm_results)

final_matrix <- do.call(rbind, matrix_list)
在随机种子数据上演示

set.seed(12262018)
data_tools <- c("sas", "stata", "spss", "python", "r", "julia")

d <- data.frame(
  group = sample(data_tools, 500, replace=TRUE),
  int = sample(1:15, 500, replace=TRUE),
  Qend = rnorm(500) / 100,
  Rainfall = rnorm(500) * 10
)
结果


下面是一个基本的R解决方案:

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 
要以HTML的表格格式呈现输出,可以使用knitr::kable

…在呈现降价后生成以下输出:


下面是一个基本的R解决方案:

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 
要以HTML的表格格式呈现输出,可以使用knitr::kable

…在呈现降价后生成以下输出:


这里只有几行:

library(tidyverse)
library(broom)
# create grouped dataframe:
df_g <- df %>% group_by(CatChro)
df_g %>% do(tidy(lm(Qend ~ Rainfall, data = .))) %>% 
   select(CatChro, term, estimate) %>% spread(term, estimate) %>% 
   left_join(df_g %>% do(glance(lm(Qend ~ Rainfall, data = .))) %>%
   select(CatChro, r.squared, adj.r.squared, p.value), by = "CatChro")
这将为您提供:

df_g %>% do(tidy(lm(Qend ~ Rainfall, data = .))) %>% 
  select(CatChro, term, estimate) %>% spread(term, estimate)
A tibble: 10 x 3
Groups:   CatChro [10]
   CatChro `(Intercept)` Rainfall
   <chr>           <dbl>    <dbl>
 1 A3D1          0.0119  0.000409
 2 A3D2          0.0236  0.000543
 3 A3D3          0.0221  0.000145
 4 A3D4          0.00930 0.000661

Glance为您提供了每个车型所需的汇总统计信息。模型是按组索引的,这里是CatChro,因此很容易将它们合并到前面的数据帧中,这就是代码的其余部分。

这里只有几行:

library(tidyverse)
library(broom)
# create grouped dataframe:
df_g <- df %>% group_by(CatChro)
df_g %>% do(tidy(lm(Qend ~ Rainfall, data = .))) %>% 
   select(CatChro, term, estimate) %>% spread(term, estimate) %>% 
   left_join(df_g %>% do(glance(lm(Qend ~ Rainfall, data = .))) %>%
   select(CatChro, r.squared, adj.r.squared, p.value), by = "CatChro")
这将为您提供:

df_g %>% do(tidy(lm(Qend ~ Rainfall, data = .))) %>% 
  select(CatChro, term, estimate) %>% spread(term, estimate)
A tibble: 10 x 3
Groups:   CatChro [10]
   CatChro `(Intercept)` Rainfall
   <chr>           <dbl>    <dbl>
 1 A3D1          0.0119  0.000409
 2 A3D2          0.0236  0.000543
 3 A3D3          0.0221  0.000145
 4 A3D4          0.00930 0.000661
Glance为您提供了每个车型所需的汇总统计信息。模型是按组索引的,这里是CatChro,因此很容易将它们合并到前面的数据帧中,这就是代码的其余部分。

另一种解决方案,使用lme4::lmList。lmList生成的对象的summary方法几乎可以实现您想要的所有功能,尽管它不存储p值,这是我必须在下面添加的内容

m <- lme4::lmList(Qend~Rainfall|CatChro,data=d)
s <- summary(m)
pvals <- apply(s$fstatistic,1,function(x) pf(x[1],x[2],x[3],lower.tail=FALSE))
data.frame(intercept=coef(s)[,"Estimate","(Intercept)"],
           slope=coef(s)[,"Estimate","Rainfall"],
           r.squared=s$r.squared,
           adj.r.squared=unlist(s$adj.r.squared),
           p.value=pvals)
另一个解决方案是lme4::lmList。lmList生成的对象的summary方法几乎可以实现您想要的所有功能,尽管它不存储p值,这是我必须在下面添加的内容

m <- lme4::lmList(Qend~Rainfall|CatChro,data=d)
s <- summary(m)
pvals <- apply(s$fstatistic,1,function(x) pf(x[1],x[2],x[3],lower.tail=FALSE))
data.frame(intercept=coef(s)[,"Estimate","(Intercept)"],
           slope=coef(s)[,"Estimate","Rainfall"],
           r.squared=s$r.squared,
           adj.r.squared=unlist(s$adj.r.squared),
           p.value=pvals)

打包扫帚,函数整洁和浏览除了扫帚,您可能还可以通过在数据框上使用group_by将其简化为一行。然而,如果没有一个最小的可复制的例子,这是很难帮助的;而glance给出了r平方和p值。信息分散。这只是一个lm。现在,这并不重要,因为我已经手动提取了我想要的信息。但是现在,我怎么把它制成表格?至于怎么把它制成表格,你说的表格是什么意思?你能告诉我们你想要的结果吗?甚至可以提供一些示例数据?注意-我认为您的原始代码中有一个错误,下面的许多答案都没有重复。截距不是在系数[2,2]处,而是在系数[1,1]包扫帚处,除扫帚外,您可能还可以通过在数据帧上使用group_by将其简化为一行。然而,如果没有一个最小的可复制的例子,这是很难帮助的;而glance给出了r平方和p值。信息分散。这只是一个lm。现在,这并不重要,因为我已经手动提取了我想要的信息。但是现在,我怎么把它制成表格?至于怎么把它制成表格,你说的表格是什么意思?你能告诉我们你想要的结果吗?甚至可以提供一些示例数据?注意-我认为您的原始代码中有一个错误,下面的许多答案都没有重复。截距不是在系数[2,2],而是在系数[1,1]处,非常感谢!这是相当紧凑,工作得很好。额外的表格格式是一个巨大的奖励。非常感谢!这是相当紧凑,工作得很好。额外的表格格式是一个巨大的奖励。嘿。。。非常感谢你的回答。我能理解。然而,当它到达最后两条线时,出现了一个问题。我收到了以下错误消息:>matrix\u list final\u matrix我希望您在通话中使用了数据组:比亚迪、d$CatChro、lm\u结果。很抱歉,我无法测试您的实际数据,因为链接是forbi的
在工作机器上工作。我们总是特别要求未来的读者在文章正文中包含数据样本。R的dputheadmydata非常适合这个。嘿。。。非常感谢你的回答。我能理解。然而,当它到达最后两条线时,出现了一个问题。我收到了以下错误消息:>matrix\u list final\u matrix我希望您在通话中使用了数据组:比亚迪、d$CatChro、lm\u结果。很抱歉,我无法测试您的实际数据,因为工作机器上禁止链接。我们总是特别要求未来的读者在文章正文中包含数据样本。R的dputheadmydata非常适合这个。嗨@coffeinjunky。非常感谢你。我可以遵循代码,但在运行时遇到了一些问题。问题之一是,显然,即使在我安装了tidyverse之后,它也不能使用。此外,我还必须安装PackageTityr。但即使在那之后,我还是收到了以下错误消息:error in UseMethodgroup_by_uu:还有这个错误消息:error in evallhs,parent,parent:object'df_g'not found很抱歉听到你有问题,但我不确定我知道的足够多来解决它们,因为对我来说一切都很好。一般来说,如果您想继续使用R,我建议您研究split-apply-combine范例,熟悉tidy data和dplyr.Hi@coffeinjunky。非常感谢你。我可以遵循代码,但在运行时遇到了一些问题。问题之一是,显然,即使在我安装了tidyverse之后,它也不能使用。此外,我还必须安装PackageTityr。但即使在那之后,我还是收到了以下错误消息:error in UseMethodgroup_by_uu:还有这个错误消息:error in evallhs,parent,parent:object'df_g'not found很抱歉听到你有问题,但我不确定我知道的足够多来解决它们,因为对我来说一切都很好。一般来说,如果您想继续使用R,我建议您研究split-apply-combine范例,熟悉tidy data和dplyr。