1

I am trying to add labels into a factor with Latex expressions with latex2exp with the following reproducible code:

library(latex2exp)

  datplot <- setNames(data.frame(matrix(ncol = 4,nrow = 216000)), c('Fz','Cz','Pz','bta'))
  datplot$bta <- rep(c('b0','b1','b1-b0'), each=72000)
  datplot$bta <- factor(datplot$bta, labels=c("b0" = TeX("$\beta_0\cdot x\; (x=0)$"),
                                              "b1" = TeX("$\beta_0+\beta_1\cdot x\; (x=1)$"),
                                              "b1-b0" = TeX("$\beta_0+\beta_1\cdot x-\beta_0= \beta_1\cdot x\; (x=1)$")))

Unfortunately, I keep having the following error and I don't know the source of it:

Error: '\c' is an unrecognized escape in character string starting ""$\beta_0\c"

However, I've tried the plotmath expressions with this interpreter and they are all correct.

zephryl
  • 14,633
  • 3
  • 11
  • 30
Unai Vicente
  • 367
  • 3
  • 10
  • 3
    You need to escape backslashes in strings in R. Each ```\``` should be a ```\\``` – Allan Cameron Feb 14 '23 at 13:32
  • Oh interesting, I thought it would take all in the original expression inside the $. Thanks very much! – Unai Vicente Feb 14 '23 at 14:27
  • 2
    You can use new "raw" strings for R. See `r"{$\beta_0\cdot x\; (x=0)$}"`. (Wrap in `r"{` and `}"` instead of just `"`.) – r2evans Feb 14 '23 at 14:41
  • That's great, didn't know there were raw strings in R as well. Thanks! – Unai Vicente Feb 14 '23 at 15:07
  • 1
    The concept of "Raw character constants" was introduced in R-4.0.0. Apparently it also works with parens and anything matching. For instance, if the real string has both `}` and `)` in it (that might disrupt the parsing), one could use pipes: `r"{$\beta_0\cdot x\; (x=0)$}"`, `r"($\beta_0\cdot x\; (x=0)$)"`, and `r"|$\beta_0\cdot x\; (x=0)$|"` all work the same. – r2evans Feb 14 '23 at 15:33
  • 1
    @r2evans Interesting, at the `?"'"` help page `|` isn't included as an option, only `{}`, `()`, `[]` with optional dashes. But it certainly works. – Gregor Thomas Feb 14 '23 at 16:15
  • @GregorThomas I didn't read the man page (though now I have, thanks), I did the next-best-thing: tried random things. And given a little more effort, I've ruled out just about everything else. Odd that `|` is not listed, but it works, both with and without leading/trailing dashes, so both `r"|$\beta_0\cdot x\; (x=0)$|"` and `r"-----|$\beta_0\cdot x\; (x=0)$|-----"` work :-) – r2evans Feb 14 '23 at 16:20

0 Answers0