【发布时间】:2015-08-13 01:57:26
【问题描述】:
我有一个因子向量。有些值可以重复。这些值事先不知道,但可以排序。例如,
x1 <- factor(c("A", "C", "C", "A", "B" ), levels=c("A", "B", "C"))
x2 <- factor(c("E", "C", "C", "D", "B" ), levels=c("B", "C", "D", "E"))
我想创建另一个向量,其中每个值都是“last”、“other”或“first”,并且这些值对应于第一个或最后一个因子级别。在上述情况下,结果向量 y1 必须是 c("first", "last", "last", "first", "other"),而 y2 必须是 c("last", "other", "other", "other", "first")。
目前,我是这样做的:
f2l <- function(x) {
x <- as.numeric(x)
y <- rep("other", length(x))
y[ x == max(x) ] <- "last"
y[ x == min(x) ] <- "first"
y
}
这按预期工作,但我想知道是否有更有效的解决方案。
【问题讨论】:
-
你可以考虑使用
data.table,a la进行一种合并
标签: r