【问题标题】:R plotmath - how to display an apostropheR plotmath - 如何显示撇号
【发布时间】:2016-05-09 15:38:08
【问题描述】:

我正在尝试使用tableGrob在表格中为下面的列名打印撇号

"Kendall's~tau"

最终结果是整个标签为斜体,而 ~tau 未被解释:

如何正确指定?

我不认为它有帮助,但这是我为 tableGrob 指定的主题:

table_theme <-  ttheme_default(
   core = list(fg_params=list(fontsize = 6)),
   colhead = list(fg_params=list(fontsize = 6, parse=TRUE)),
   rowhead = list(fg_params=list(fontsize = 6, parse=TRUE)),
   padding = unit(c(2, 3), "mm"))

列名通过 grDevices 中的 plotmath 进行解释——在 R 中生成的图形中指定数学注释的标准方法。

同样它与如何指定表达式本身无关,但这里是表构造函数:

tableGrob(stats_df,
     theme = table_theme, 
     rows = c("Kendall's~tau"))

这是一个可重现的例子:

library(gridExtra)
library(grid)
data(iris)
table_theme <-  ttheme_default(rowhead = list(fg_params=list(parse=TRUE)))
grid.table(head(iris),
       rows = c(letters[c(1:4)], "plotmath~works~omega", "Kendall's~tau"),
       theme = table_theme)

【问题讨论】:

  • 这对我不起作用。我似乎无法添加撇号! “” '' `` 或 ~~ 分隔符或前面带有 \ 的转义分隔符似乎都不起作用。我错过了什么?示例: qplot(1:10,1:10)+annotate("text",x=2,y=2,label="Matt's diner~3^2",parse=T) 给出: 解析错误(文本 =文本[[i]])

标签: r plotmath


【解决方案1】:

这行得通:

library(gridExtra)
library(grid)
data(iris)
table_theme <-  ttheme_default(rowhead = list(fg_params=list(parse=TRUE)))
grid.table(head(iris),
  rows = c(letters[c(1:4)], "plotmath~works~omega", "Kendall's"~tau),
  theme = table_theme)

【讨论】:

    【解决方案2】:

    尝试在表达式中使用反斜杠,例如 "Kendall\'s~tau"。那么它应该可以工作了。

    【讨论】:

      【解决方案3】:

      我尝试使用带有表达式的撇号在 ggplot 中绘图。在我的数据库中,在表达式中使用 ' 无效,但这有效

      expression(paste(u,"'",(t),sep=""))
      

      但是这种“粘贴”也会导致子索引表达式表达式(U[0])的不良行为。因此,将两者一起使用,这个有效

      paste(expression(paste("u","'",sep="")),"/U[0]",sep="")
      

      如果有人知道更简单的方法,我会很高兴。

      【讨论】:

      • 你能正确地形成你的答案吗?
      【解决方案4】:

      如果您的撇号嵌入到较长的字符串中,以及像 ~ 这样的特殊符号,这些解决方案将不起作用。我发现唯一可行的方法是使用正则表达式替换。

      #This doesn't work
      stringWithApostrophe="Matt's and Louise's diner~...and~also Ben's diner~X^2"
      qplot(1:10,1:10)+annotate("text",x=2,y=4,label=stringWithApostrophe,parse=T)
      

      错误:“解析错误(text = text[[i]]): :1:5: 意外字符串常量”

      问题是波浪线和撇号等特殊字符出现在同一个引用段中。所以你必须将“Matt's”与“Louise's”和“~”分开。这是执行此操作的代码。

      stringWithApostrophe2<-stringr::str_replace_all(pattern = "([^~()*]*'[^~()*']*)",replacement = "\"\\1\"",string=stringWithApostrophe)
      qplot(1:10,1:10)+annotate("text",x=2,y=8,hjust=0,label=stringWithApostrophe2,parse=T)
      

      绘图成功。 R 中的 plotmath 正确解析的最终表达式是: ""Matt 和 Louise 的餐厅"~...and~"也是 Ben 的餐厅"~X^2"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 2019-02-17
        • 2014-02-07
        • 2021-05-06
        • 1970-01-01
        • 2020-09-18
        相关资源
        最近更新 更多