[英]How to gsub('%', '\%', … in R?
I want to export a latex table with a units column that has the percent (%) symbol. 我想导出带有单位栏的乳胶表,该单位栏具有百分比(%)符号。
library(xtable)
foo <- data.frame(units='%', citation = '\\citep{authorYYYYabc}')
print(xtable(foo), sanitize.text.function = function(x) {x})
note: above code has been changed since Joris' answer. 注意:以上代码自Joris回答以来已更改。
In this case, the '%' is interpreted as a comment by LaTeX. 在这种情况下,LaTeX将'%'解释为注释。
I have tried 我努力了
gsub('%', '\\%', foo)
returns 回报
[1] "1"
how can I convert the % to \\% so that LaTex comments it out? 如何将%转换为\\%,以便LaTex注释掉?
This question is a little bit like a previous question " can R paste('\\')?" 这个问题有点像先前的问题“ R可以粘贴('\\')吗?” ; ; even polishing the same table, but I can't figure out this particular case. 甚至抛光同一张桌子,但我无法弄清楚这种特殊情况。
I'm not sure if I understand you completely correctly. 我不确定我是否完全了解您。 If I do xtable(foo), then the % is correctly escaped : 如果我执行xtable(foo),则%可以正确转义:
...
\hline
1 & \% \\
\hline
...
If you want to make an escape slash for something else, you need a quadruple one in gsub : 如果要为其他内容加上转义斜线,则需要在gsub中添加四倍的转义:
> x <- gsub('%', '\\\\%', foo[,1])
> x
[1] "\\%"
> cat(x,"\n")
\%
Mind you, you cannot gsub in a dataframe, only in a vector. 提醒您,您不能在数据框中gsub,而只能在向量中gsub。 This can be shown by 这可以显示为
> as.character(foo)
[1] "1"
Combining Joris' answer with the codes in the comment: 将Joris的答案与注释中的代码结合起来:
library(xtable)
foo <- data.frame(units='%', citation = '\\citep{authorYYYYabc}')
print(xtable(foo), sanitize.text.function = function(x)gsub('%', '\\\\%', x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.