Search code examples
rcoefficientscoefplot

Create a coefplot from matrix


I am trying to create a coefplot (https://lrberge.github.io/fixest/reference/coefplot.html) from a matrix. (This is to show linear combinations of interaction terms, see below example code.) The documentation - see above link - indicates that this should be possible: object can be a matrix of coefficients table. Alternatively, I should be able to provide a vector of estimates, plus confidence interval information, to create the coefplot. I haven't been able to do so.

I have tried the following:

##packages and libraries required: 
##fixest
##biostat3

library(biostat3)
library(fixest)

##load example data
data(base_did)
base_inter = base_did

##Run simple regression with interactions
A <- lm(y ~factor(period)*treat, base_inter)

##Create linear combinations
C<-lincom(A,c("treat","treat+factor(period)2:treat","treat+factor(period)3:treat", "treat+factor(period)10:treat"))

##Transform to matrix
T<-as.matrix(C)

##Remove unnecessary information and dimension names
T<-T[,1:3]
dimnames(T) <- NULL

##run coefplot from fixest
fixest::coefplot(T[,1],ci_low=T[,2],ci_high=T[,3])

I get an error:

Error in data.frame(estimate = estimate, ci_low = ci_low, ci_high = ci_high,  : 
  arguments imply differing number of rows: 4, 0

I don't understand this, because the matrix T has three columns with four rows - so dimensions should be correct.

    [,1]       [,2]       [,3]     
[1,] -1.061001  -2.99068   0.8686775
[2,] -0.7100586 -2.639737  1.21962  
[3,] 1.458543   -0.4711357 3.388222 
[4,] 7.90124    5.971561   9.830918 

Solution

  • While your matrices C and T look like matrices of numbers they are actually matrices of lists. Hence, T[, 1], ... are lists too. To fix your issue you could use apply to unlist the columns before passing them to fixest::coefplot:

    library(biostat3)
    library(fixest)
    
    T <- apply(T, 2, unlist)
    
    ## run coefplot from fixest
    fixest::coefplot(
      T[, 1],
      ci_low = T[, 2],
      ci_high = T[, 3]
    )