为什么这段代码:as.factor(c("U201C", '"3', "1", "2", "U00B5"))
在每个操作系统上返回不同的因子级别顺序?
:
> as.factor(c("U201C",'"3', "1", "2","U00B5"))
[1] " "3 1 2 µ
Levels: µ " 1 2 "3
> as.factor(c("U201C",'"3', "1", "2","U00B5"))
[1] " "3 1 2 µ
Levels: "3 " µ 1 2
Mac:
>as.factor(c("U201C",'"3', "1", "2","U00B5"))
[1] " "3 1 2 µ
Levels: "3 " 1 2 µ
我有一些学生提交了一份包含as.numeric(as.factor(dat$var))
的rmardknow作业。虽然这不是一种好的编码方式,但是输出中的不一致会导致很多混乱和浪费时间。
不仅仅是Unicode,不仅仅是R;sort
通常(甚至在*nix命令sort
中)可以是特定于语言环境的。需要在所有机器上通过Sys.setlocale
设置LC_COLLATE
(假设为"C"
)(根据@alistaire的评论)来消除差异。
对于我来说,在Windows(7)上:
sort(c("Abc", "abc", "_abc", "ABC"))
[1] "_abc" "abc" "Abc" "ABC"
而在Linux (Ubuntu 12.04…哇,我需要升级那台机器)我得到
sort(c("Abc", "abc", "_abc", "ABC"))
[1] "abc" "_abc" "Abc" "ABC"
通过
设置区域设置Sys.setlocale("LC_COLLATE", "C")
为
sort(c("Abc", "abc", "_abc", "ABC"))
[1] "ABC" "Abc" "_abc" "abc"
在两台机器上,完全相同。
sort
的*nix man
页面给出了粗体警告
*** WARNING *** The locale specified by the environment affects sort order. Set LC_ALL=C to get the traditional sort order that uses native byte values.
Update:看起来我在包括Unicode字符时再现了这个问题。这个问题可以追溯到sort
-尝试在您的示例中对向量进行排序。我似乎无法将区域设置(LC_COLLATE
或LC_CTYPE
)更改为"en_AU.UTF-8"
,这将是一个潜在的解决方案。
'factor'结构期望转换为字符值,因此需要用某种字体或其他字体进行编码。默认是特定于操作系统的。词法排序顺序遵循locale。
在某种程度上,@Roland先前对这个问题的回答明确了语言环境问题,但没有明确编码问题:因子的默认("自动")排序是R规范的一部分吗?字母吗?所有平台都一样吗?
我已尝试更改区域设置,但无法解决此问题。然而,考虑到我们可以将这个问题追溯到sort
函数,一个可能的替代方案是重新定义factor
和as.factor
函数,而不使用sort
函数。
as.factor2 <- function(x){
if (is.factor(x))
x
else if (!is.object(x) && is.integer(x)) {
levels <- unique.default(x) # Removed sort()
f <- match(x, levels)
levels(f) <- as.character(levels)
class(f) <- "factor"
f
}
else factor2(x)
}
factor2 <- function (x = character(), levels, labels = levels, exclude = NA,
ordered = is.ordered(x), nmax = NA)
{
if (is.null(x))
x <- character()
nx <- names(x)
if (missing(levels)) {
y <- unique(x, nmax = nmax)
ind <- 1:length(y) # Changed from sort.list(y)
y <- as.character(y)
levels <- unique(y[ind])
}
force(ordered)
exclude <- as.vector(exclude, typeof(x))
x <- as.character(x)
levels <- levels[is.na(match(levels, exclude))]
f <- match(x, levels)
if (!is.null(nx))
names(f) <- nx
nl <- length(labels)
nL <- length(levels)
if (!any(nl == c(1L, nL)))
stop(gettextf("invalid 'labels'; length %d should be 1 or %d",
nl, nL), domain = NA)
levels(f) <- if (nl == nL)
as.character(labels)
else paste0(labels, seq_along(levels))
class(f) <- c(if (ordered) "ordered", "factor")
f
}
我们现在可以这样调用as.factor2
:
as.factor2(c("U201C",'"3', "1", "2","U00B5"))
# [1] “ "3 1 2 µ
# Levels: "3 “ 1 2 µ
我不会说这是解决你问题的办法;这更像是一种变通。特别是因为这涉及到教学生,我宁愿不重新创建基R函数。希望其他人能提供一个更简单的解决方案。