Search code examples
rstargazer

How to include square brackets in regression and stargazer output


I am currently writing a short r code to run a regression but one of co-variate (CAR[-11,0]) contains special characters, and it reports error "object 'CAR[-11,0]' not found". I have tried to cover CAR[-11,0] with '`' symbol.Here is my r code to run the regression.

library(stargazer)
set.seed(123)
n <- 200
df <- data.frame(
  risk1 = rnorm(n),
  risk2 = rnorm(n),
  `CAR[-11,0]` = rnorm(n),
  `CAR[-27,0]` = rnorm(n),
  `CAR[-18,0]` = rnorm(n),
  lev = rnorm(n),
  grow = rnorm(n),
  fcf = rnorm(n),
  fage = rnorm(n),
  roe = rnorm(n),
  top1 = rnorm(n),
  dual = rnorm(n),
  board = rnorm(n),
  comp = rnorm(n),
  soe = rnorm(n),
  year = sample(2000:2006, n, replace = TRUE),
  f006v_pub001 = sample(0:1, n, replace = TRUE),
  check.names = FALSE
)
main_regression_1_0_A <- lm(risk1 ~ `CAR[-11,0]` + factor(year) + factor(f006v_pub001), data = df)
stargazer(main_regression_1_0_A, type = "text")

I have tried replace all of special characters (including[ ] , -) with underscore. It works, but I really want to keep them in variable name to make them readable. Here is the r code with underscore:

set.seed(123)
n <- 200
df <- data.frame(
  risk1 = rnorm(n),
  risk2 = rnorm(n),
  CAR_11_0 = rnorm(n),
  CAR_27_0 = rnorm(n),
  CAR_18_0 = rnorm(n),
  lev = rnorm(n),
  grow = rnorm(n),
  fcf = rnorm(n),
  fage = rnorm(n),
  roe = rnorm(n),
  top1 = rnorm(n),
  dual = rnorm(n),
  board = rnorm(n),
  comp = rnorm(n),
  soe = rnorm(n),
  year = sample(2000:2006, n, replace = TRUE),
  f006v_pub001 = sample(0:1, n, replace = TRUE),
  check.names = FALSE
)
main_regression_1_0_A <- lm(risk1 ~ CAR_11_0 + factor(year) + factor(f006v_pub001), data = df)
library(stargazer)
stargazer(main_regression_1_0_A, type = "text")

Solution

  • Use check.names = FALSE

    df <- data.frame(
      risk1 = rnorm(n),
      risk2 = rnorm(n),
      `CAR[-11,0]` = rnorm(n),
      `CAR[-27,0]` = rnorm(n),
      `CAR[-18,0]` = rnorm(n),
      lev = rnorm(n),
      grow = rnorm(n),
      fcf = rnorm(n),
      fage = rnorm(n),
      roe = rnorm(n),
      top1 = rnorm(n),
      dual = rnorm(n),
      board = rnorm(n),
      comp = rnorm(n),
      soe = rnorm(n),
      year = sample(2000:2006, n, replace = TRUE),
      f006v_pub001 = sample(0:1, n, replace = TRUE),
      check.names = FALSE
    )