Search code examples
rstargazer

Stargazer splits character field into columns when summary=F and string contains "&"


How can I print a stargazer table when summary=F and a character column has elements containing &? summary=F prints the data table verbatim which is what I want.

Here's a case where it prints as expected:

> stargazer::stargazer(
+   data.frame(ur1=c('hot','tamale'),yum='!')
+   ,type='text',summary=F)

============
   ur1   yum
------------
1  hot    ! 
2 tamale  ! 
------------

And here the & is split into two columns.

> stargazer::stargazer(
+   data.frame(ur1=c('hot & tamale'),yum='!')
+   ,type='text',summary=F)

============
  ur1  yum  
------------
1 hot tamale
------------

The same behavior happens in html and latex modes as well. In latex it's easy to hack a fix for a character by commenting out the & a la gsub(x,pattern='&',replacement='\\&',fixed=T) but that fix doesn't work for html and replacing it with the entity & still causes the split. While it would be easy to use kable or simple markdown to print the table, I want my this kind of table to have the same style as the stargazer regression tables.

I hope someone can help! Also, I couldn't find a development repo to report it if it's a bug.

I do have the latest version of stargazer:

> devtools::session_info()
Session info ------------------
 setting  value                       
 version  R version 3.4.4 (2018-03-15)
 system   x86_64, linux-gnu           
 ui       RStudio (1.1.419)           
 language (EN)                        
 collate  en_US.UTF-8                 
 tz       Etc/UTC                     
 date     2018-09-14                  

Packages ----------------------
 stargazer     5.2.2      2018-05-30 CRAN (R 3.4.4)                   

Solution

  • It's a very hacky solution, but you could insert a tab (\t) and a backspace (\b) escape sequence right before the &. This seems to work for type = "text" and type = "html", but not type = "latex".

    dat <- data.frame(ur1=c('hot & tamale', 'hot & taco') ,yum='!')
    dat[, 1] <- gsub("&", "\t\b&", dat[, 1])
    
    stargazer::stargazer(dat, type = "text", summary=F)
    ====================
           ur1       yum
    --------------------
    1 hot & tamale  ! 
    2  hot & taco   ! 
    --------------------