dmurdoch / tables

Formula-Driven Table Generation
https://dmurdoch.github.io/tables/
13 stars 2 forks source link

toKable: handling underscores in variable names #34

Open gillesdutilh opened 2 days ago

gillesdutilh commented 2 days ago

When using toKable, variable names with underscores end up unchanged in the latex code, leading to errors rendering.

Exampe:

mydata = data.frame(
   study_arm = rep(c('A', 'B'), 5),
   score = rnorm(10))
tab = tabular(score ~ Factor(study_arm) * mean, data = mydata)
toKable(tab)

Evaluates as: \begin{tabular}{lcc} \toprule & \multicolumn{2}{c}{study_arm} \ \cmidrule(lr){2-3} & A & \multicolumn{1}{c}{B} \ & mean & \multicolumn{1}{c}{mean} \ \midrule score & $0.3444$ & $-0.4508$ \ \bottomrule \end{tabular}

The following workaround does the job:

gsub('_', '\\\\_', toKable(tab))

This one is pretty dirty and may actually break stuff, e.g., if you have mathematical expressions in your table. I could also rename my variables, but I think at least the variable name part of the string that results from toKable may safely be gsubbed as in my dirty workaround.

Thanks for considering!

dmurdoch commented 2 days ago

Another workaround would be to set the name of the column explicitly, e.g.

tab = tabular(score ~ Factor(study_arm, name = "Study\\_Arm") * mean, data = mydata)

I didn't test that that would work, but it looks safer than the gsub() approach.

In any case, this isn't really a problem with toKable(), it's a problem with toLatex(). Perhaps table_options() should have an option to escape LaTeX special characters.