Search code examples
rlogistic-regressionglmcoefplot

change coefficient names in coefplot.glm()


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.


Solution

  • 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"))