rstargazer

How can I use the coef argument in stargazer in R?


I am really confused how to use the coef argument in stargazer in R. I want to create a table with only a few of the coefficients in my regression. According to the function documentation, it should be "a list of numeric vectors that will replace the default coefficient values for each model. Element names will be used to match coefficients to individual covariates, and should therefore match covariate names". This is super unclear, since it first mentions numeric vectors, but then it mentions variables names (which are not numeric). I haven't found any examples that work in the internet (or ChatGPT). I don't understand the syntax needed to specify the coefficients/build this list. Can anyone provide an example, please?


Solution

  • The coef command in stargazer specifies a predefined value for the coefficient. You can name a list (i.e., list("a" = 1:3, "b" = 4:6)). Here is an example (using absurd coef values for clarity)

    # model
    mod <- lm(mpg ~ cyl + hp + am, data = mtcars)
    
    # table
    stargazer::stargazer(mod, 
                         coef = list(c("cyl" = 400, "hp" = 200, "am" = 600)))
    

    enter image description here

    What the help means by

    "Element names will be used to match coefficients to individual covariates, and should therefore match covariate names"

    Is saying that the names of those elements have to be the same as those in your coefficients.

    What I believe you want is a table with only specified coefficients (ie, not all three in the above model). To do that, use keep:

    stargazer::stargazer(mod, keep = c("cyl", "hp"))
    

    enter image description here