一段时间后我将返回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 <- ????
这样:
> fdata$lvl_idx
[1] 1 2 1 1 3
赞赏任何提示或技巧。
如果将因子转换为整数,则可以得到各个级别的位置:
as.integer(fdata)
## [1] 1 2 1 1 3
在某些情况下,这是违反直觉的:
f <- factor(2:4)
f
## [1] 2 3 4
## Levels: 2 3 4
as.integer(f)
## [1] 1 2 3
此外,如果您无声地强制转换为整数,例如通过使用因子作为向量索引:
LETTERS[2:4]
## [1] "B" "C" "D"
LETTERS[f]
## [1] "A" "B" "C"
在转换为character
之前转换为integer
会得到期望值。有关详细信息,请参见?factor
。
[马修·伦德伯格(Matthew Lundberg)数年前提供的解决方案并不可靠。可能是as.integer()
函数是为特定的S3类型的因子定义的。想象有人会创建一个新的因子类来保留像>=
这样的运算符。
as.myfactor <- function(x, ...) { structure(as.factor(x), class = c("myfactor", "factor")) } # and that someone 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))) }
现在这不再起作用了,它只是删除了运算符:
使用f <- as.myfactor(">=2") as.integer(f) #> [1] 2
但是此是
which()
对您想要的水平索引的任何因素都非常可靠:f <- factor(2:4)
which(levels(f) == 2)
#> [1] 1