-1

Let's say I were to execute a regression model in R:

library(data.table)
mtcars = as.data.table(mtcars)
dt = colSums(mtcars)

> dt
     mpg      cyl     disp       hp     drat       wt     qsec       vs 
 642.900  198.000 7383.100 4694.000  115.090  102.952  571.160   14.000 
      am     gear     carb 
  13.000  118.000   90.000 

model = lm(formula=mpg~cyl, data=dt)

The way I would plot the coefficients of this model would be to use the following function, from Extract regression coefficient values

:

plot_coeffs <- function(mlr_model) {
  coeffs <- coefficients(mlr_model)
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}

plot_coeffs(model)

However, this plot will not plot the coefficients in a sorted manner, e.g. greatest to least in descending order.

I have tried using order(coeffs) in the above function, but this doesn't seem to work. How does one easily plot the coefficients in decreasing order?

ShanZhengYang
  • 16,511
  • 49
  • 132
  • 234
  • Are you building the model( `lm`) on a single observation? Perhaps you need `coeffs <- coefficients(model); coeffs <- coeffs[order(coeffs)]` Here also, your example is not representative of the problem – akrun Jul 06 '17 at 12:57
  • Do you mean `lm(formula = mpg ~ cyl, data = mtcars)`? – KoenV Jul 06 '17 at 13:05

2 Answers2

1

you can order the coefficients and then plot the data:

model = lm(formula=mpg~cyl, data=mtcars)

coeffs <- coefficients(model)
coeffsord <- coeffs[order(coeffs)]

barplot(coeffsord, col="#3F97D0", xaxt='n', main="Regression Coefficients")
text(1:2, labels = names(coeffsord), srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
Wietze314
  • 5,942
  • 2
  • 21
  • 40
1

You can also adapt your function to sort the coefficients:

plot_coeffs_S <- function(mlr_model) {
  coeffs <- sort(coefficients(mlr_model), decreasing = TRUE)  ### changed
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
KoenV
  • 4,113
  • 2
  • 23
  • 38