如何在R包函数中使用非ASCII符号(例如£)?

18

我在我的一个 R 包中有一个简单的函数,其中一个参数为 symbol = "£"

formatPound <- function(x, digits = 2, nsmall = 2, symbol = "£"){ 
  paste(symbol, format(x, digits = digits, nsmall = nsmall)) 
}

但是运行R CMD check时,我收到了以下警告:

* checking R files for non-ASCII characters ... WARNING
Found the following files with non-ASCII characters:
  formatters.R

问题出在那个 £ 符号上。如果我把它替换成一个合法的 ASCII 字符,比如 $,警告就会消失。

问题:如何在函数参数中使用 £,而不触发 R CMD check 警告?


也许可以通过指定编码参数,并设置为latin1或utf-8来实现? - Dirk Eddelbuettel
2个回答

16

看起来 "编写 R 扩展" 在第 1.7.1 节 "编码问题" 中涵盖了此内容。


此页面中的建议之一是使用 Unicode 编码 \uxxxx。由于 £ 是 Unicode 00A3,您可以使用:

formatPound <- function(x, digits=2, nsmall=2, symbol="\u00A3"){
  paste(symbol, format(x, digits=digits, nsmall=nsmall))
}


formatPound(123.45)
[1] "£ 123.45"

1
谢谢。这真的很有帮助。我已经编辑了你的答案,使其在建议方面更具体。(顺便说一句,通过谷歌搜索此警告消息只会得到列出此警告的软件包列表!)。 - Andrie
这种方法的问题在于,例如roxygen2 v6.0.1生成的Rd文件会在稍后的R CMD检查中引起错误(非ASCII字符)。请参见下面的解决方法。 - Viliam Simko

6

作为解决方法,您可以使用intToUtf8()函数:

# this causes errors (non-ASCII chars)
f <- function(symbol = "➛")

# this also causes errors in Rd files (non-ASCII chars)
f <- function(symbol = "\u279B")

# this is ok
f <- function(symbol = intToUtf8(0x279B))

1
我还发现testthat包在运行包含UTF-8字符的测试时存在问题。 - Viliam Simko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接