用 Latex 代码替换字符串向量中的重音符号
定义:
df <- data.frame(name=c("México","Michoacán"),dat=c(1,2))
st
> df
name dat
1 México 1
2 Michoacán 2
当我使用 xtable
将此表打印到 .tex
文件时,重音字符会出现乱码,这并不奇怪。
我想用正确的 Latex
格式替换重音,例如:
> df
name dat
1 M\'{e}xico 1
2 Michoac\'{a}n 2
请注意,在真实数据集中,有许多不同的名称具有不同的重音字母,但都具有相同类型的重音(即正斜杠),因此唯一的\'{.}
中需要更改的是代替点的字母。
在尝试一位读者的建议时,我做了以下操作:
> df <- data.frame(name=c("México","Michoacán"),dat=c(1,2))
> df
name dat
1 México 1
2 Michoacán 2
> df$name <- sub("é", "\\\\'{e}", df$name,)
> df
name dat
1 M\\'{e}xico 1
2 Michoacán 2
> capture.output(
+ print(xtable(df)),
+ file = "../paper/rTables.tex", append = FALSE)
当我在记事本中打开rTables.tex文件时:
% latex table generated in R 2.13.1 by xtable 1.5-6 package
% Fri Jul 15 13:19:17 2011
\begin{table}[ht]
\begin{center}
\begin{tabular}{rlr}
\hline
& name & dat \\
\hline
1 & M$\backslash$'\{e\}xico & 1.00 \\
2 & Michoacán & 2.00 \\
\hline
\end{tabular}
\end{center}
\end{table}
这不是所需要的。
Define:
df <- data.frame(name=c("México","Michoacán"),dat=c(1,2))
s.t.
> df
name dat
1 México 1
2 Michoacán 2
When I print this table to a .tex
file using xtable
the accented characters get garbled, which is no surprise.
I would like to replace accents with proper Latex
formatting e.g.:
> df
name dat
1 M\'{e}xico 1
2 Michoac\'{a}n 2
Please note in real dataset there are many different names with different accented letters but all with same type of accent (i.e. foward-slash), so the only thing that needs to change in \'{.}
is the letter in place of the dot.
In trying one reader's suggestion i did the following:
> df <- data.frame(name=c("México","Michoacán"),dat=c(1,2))
> df
name dat
1 México 1
2 Michoacán 2
> df$name <- sub("é", "\\\\'{e}", df$name,)
> df
name dat
1 M\\'{e}xico 1
2 Michoacán 2
> capture.output(
+ print(xtable(df)),
+ file = "../paper/rTables.tex", append = FALSE)
When I opened the rTables.tex file in Notepad:
% latex table generated in R 2.13.1 by xtable 1.5-6 package
% Fri Jul 15 13:19:17 2011
\begin{table}[ht]
\begin{center}
\begin{tabular}{rlr}
\hline
& name & dat \\
\hline
1 & M$\backslash
This is not what is needed.
\{e\}xico & 1.00 \\
2 & Michoacán & 2.00 \\
\hline
\end{tabular}
\end{center}
\end{table}
This is not what is needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
stringr
包,一次替换每种类型的重音字符。Use the
stringr
package, and replace each type of accented character one at a time.我认为问题在于这种情况要求 xtable 尝试将奇怪的字符转换为 LaTeX。尝试按如下方式重写
sanitize.text.function
:在我的系统上输出如下:
不过,这样做可能会破坏其他
LaTeX
标记,因此请注意的。I think the problem is that this case is asking a lot of
xtable
's attempts to convert strange characters toLaTeX
. Try overridingsanitize.text.function
as follows:which on my system outputs this:
It might be that other
LaTeX
markup may be broken by doing this, though, so be aware of that.