2

I would like to plot a coefplot.glm() with costumized coefficient names.

Consider the following code:

coefplot::coefplot.glm(lm(rbinom(1000,1,.5) ~ rnorm(1000,50,2) + rbinom(1000,1,prob=0.63) + rpois(1000, 2)))

This works fine but gives me the original variable names; I would like to change them inside the coefplot.glm() call to c("x1", "x2", "x3", "Intercept"). [I am actually working with factorized data and renaming it isn't really easily possible - the renaming would be another imported vector]

I tried

coefplot::coefplot.glm(lm(rbinom(1000,1,.5) ~ rnorm(1000,50,2) + rbinom(1000,1,prob=0.63) + rpois(1000, 2)),
               newNames = c("1", "2", "3", "Interc"))

But this yields

Error in mapvalues(x, from = names(replace), to = replace, warn_missing = warn_missing) : from and to vectors are not the same length.

Ivo
  • 3,890
  • 5
  • 22
  • 53

2 Answers2

0

What about

data <- data.frame(y=rbinom(1000,1,.5) ,x1=rnorm(1000,50,2),x2=rbinom(1000,1,prob=0.63),x3=rpois(1000, 2))
model<-lm(y~ x1 +x2  +x3 ,data=data)
coefplot::coefplot.glm(model)
  • Thank you! Unfortunately, I would need to assign the names from within the `coefplot.glm()` call (I changed the question accordingly. – Ivo Nov 25 '19 at 17:12
0

You needed a named vector, and it's not so straightforward if you want it inside coefplot.glm, you can try below:

# create a function first for your lm
f = function(){
lm(rbinom(1000,1,.5) ~ rnorm(1000,50,2) + rbinom(1000,1,prob=0.63) + rpois(1000, 2))
}

With the function, you can call it twice, first for the plot, second time to get the names

coefplot::coefplot.glm(f(),
newNames = setNames(c("Interc", "3", "2", "1"),names(coefficients(f())))
)

Or you just do:

library(ggplot2)
coefplot::coefplot.glm(fit) + scale_y_discrete(labels=c("Interc", "3", "2", "1"))
StupidWolf
  • 45,075
  • 17
  • 40
  • 72