r - 如何按列对摘要的输出进行排序?

标签 r

我想按 p 值对摘要输出进行排序 我试过了

lm.fit <- lm(TARGET ~ .,train)
df<-summary(lm.fit)

colnames(df,c("Predictor","Estimate","StdError","tvalue","pvalue","signifcodes"))
rev(sort(lm.fit$pvalue)) -> cf

但我收到错误

Warning message in if (do.NULL) NULL else if (nc > 0L) paste0(prefix, seq_len(nc)) else character(): "the condition has length > 1 and only the first element will be used" Error in if (do.NULL) NULL else if (nc 0L) paste0(prefix, seq_len(nc)) else character(): argument is not interpretable as logical Traceback:

  1. colnames(df, c("Predictor", "Estimate", "StdError", "tvalue", . "pvalue", "signifcodes"))

最佳答案

summary获得的df对象不是数据框或矩阵,colnames需要以下内容:

a matrix-like R object, with at least two dimensions

您可以提取系数,然后确定顺序和排序。这是解决此问题的一种方法:

lm.fit <- lm(mpg ~ ., mtcars)

smry.lm <- summary(lm.fit)
coef.lm <- coef(smry.lm)

i <- order(coef.lm[,4], decreasing = TRUE)
coef.lm[i, ]

使用broom,您还可以执行以下操作:

library(broom)

coef.tidy <- tidy(lm.fit)
colnames(coef.tidy) <- c("Predictor", "Estimate", "StdError", "tvalue", "pvalue")
coef.tidy[order(coef.tidy$pvalue, decreasing = TRUE), ]

输出

   Predictor   Estimate StdError tvalue pvalue
   <chr>          <dbl>    <dbl>  <dbl>  <dbl>
 1 cyl          -0.111    1.05   -0.107 0.916 
 2 vs            0.318    2.10    0.151 0.881 
 3 carb         -0.199    0.829  -0.241 0.812 
 4 gear          0.655    1.49    0.439 0.665 
 5 drat          0.787    1.64    0.481 0.635 
 6 (Intercept)  12.3     18.7     0.657 0.518 
 7 disp          0.0133   0.0179  0.747 0.463 
 8 hp           -0.0215   0.0218 -0.987 0.335 
 9 qsec          0.821    0.731   1.12  0.274 
10 am            2.52     2.06    1.23  0.234 
11 wt           -3.72     1.89   -1.96  0.0633

关于r - 如何按列对摘要的输出进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67527660/

相关文章:

重构任意嵌套列表

R ggplot : Change Grouped Boxplot Median line

r - adaBoost 中 R 中的 GBM ~ predict() 值位于 [0,1] 之外

r - ggplot geom_errorbarh 错误(输入为连续时需要离散,但输入为离散时需要连续)

R Shiny : how to create a matrix with numericInput as elements

r - NA 在 R 中的表现如何

r - 为列表中的每个元素创建新的数据框

r - ggplot中的条形图

r - 在 R 中按颜色/子组对加权网络中的 iGraph 顶点进行分组

r - 来自多个数据框列的值到一个向量中