在级别中提取因子的值位置

Hed*_*hog 4 r r-factor

一段时间后我回到了R,以下让我难过:

我想在facor级别列表中建立一个位置因子值列表.例:

> data = c("a", "b", "a","a","c")
> fdata = factor(data)
> fdata
[1] a b a a c
Levels: a b c
> fdata$lvl_idx <- ????
Run Code Online (Sandbox Code Playgroud)

这样:

> fdata$lvl_idx
[1] 1 2 1 1 3
Run Code Online (Sandbox Code Playgroud)

感谢任何提示或提示.

Mat*_*erg 8

如果将因子转换为整数,则获得级别中的位置:

as.integer(fdata)
## [1] 1 2 1 1 3
Run Code Online (Sandbox Code Playgroud)

在某些情况下,这是违反直觉的:

f <- factor(2:4)
f
## [1] 2 3 4
## Levels: 2 3 4
as.integer(f)
## [1] 1 2 3
Run Code Online (Sandbox Code Playgroud)

此外,如果您静默强制转换为整数,例如使用因子作为向量索引:

LETTERS[2:4]
## [1] "B" "C" "D"
LETTERS[f]
## [1] "A" "B" "C"
Run Code Online (Sandbox Code Playgroud)

在转换为character之前转换为integer给出预期值.详情?factor请见.


MS *_*nds 6

马修·伦德伯格(Matthew Lundberg)多年前提供的解决方案并不可靠。该as.integer()函数可能是针对特定 S3 类型的因子定义的。想象一下,有人会创建一个新的因子类来保持运算符像>=.

as.myfactor <- function(x, ...) {
  structure(as.factor(x), class = c("myfactor", "factor"))
}

# and that someone would create an S3 method for integers - it should
# only remove the operators, which makes sense...
as.integer.myfactor <- function(x, ...) {
  as.integer(gsub("(<|=|>)+", "", as.character(x)))
}
Run Code Online (Sandbox Code Playgroud)

现在这不再起作用了,它只是删除了运算符:

f <- as.myfactor(">=2")
as.integer(f)
#> [1] 2
Run Code Online (Sandbox Code Playgroud)

但这对于您想知道其级别索引的任何因素都是which()稳健的,使用:

f <- factor(2:4)
which(levels(f) == 2)
#> [1] 1
Run Code Online (Sandbox Code Playgroud)