一段时间后我回到了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
感谢任何提示或提示。
答案 0 :(得分:8)
如果将因子转换为整数,则获得级别中的位置:
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
。
答案 1 :(得分:1)
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)))
}
现在这不再起作用了,它只是删除了运算符:
f <- as.myfactor(">=2")
as.integer(f)
#> [1] 2
但是,此是健壮的,它可以使用which()
使用您想知道其水平的索引的任何因素:
f <- factor(2:4)
which(levels(f) == 2)
#> [1] 1