【问题标题】:How to use a non-ASCII symbol (e.g. £) in an R package function?如何在 R 包函数中使用非 ASCII 符号(例如 £)?
【发布时间】:2012-07-12 13:23:03
【问题描述】:

我的一个 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 ?

标签: r warnings package ascii


【解决方案1】:

看起来“编写 R 扩展”在第 1.7.1 节 "Encoding Issues" 中涵盖了这一点。


此页面中的一项建议是使用 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"

【讨论】:

  • 谢谢。这真的很有帮助。我已经编辑了您的答案,以便在其建议中更加具体。 (顺便说一句,在谷歌上搜索此警告消息只会导致包含此警告的软件包列表!)。
  • 这种方法的问题在于,例如roxygen2 v6.0.1 生成 Rd 文件,这些文件稍后会导致 R CMD 检查错误(非 ASCII 字符)。请参阅下面的解决方法。
【解决方案2】:

作为一种解决方法,您可以使用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))

【讨论】:

  • 我还发现testthat 包在运行包含 UTF-8 字符的测试时出现问题。
猜你喜欢
  • 2014-04-09
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
相关资源
最近更新 更多