I have a factor vector. Some values can be repeated. The values are not known beforehand, but can be sorted. For example,
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"))
I want to create another vector, in which each value is either "last", "other" or "first", and the values correspond to the first or last factor level. In the above case, the resulting vector y1 would have to be c("first", "last", "last", "first", "other"), while y2 would have to be c("last", "other", "other", "other", "first").
Currently, I do it like this:
f2l <- function(x) {
x <- as.numeric(x)
y <- rep("other", length(x))
y[ x == max(x) ] <- "last"
y[ x == min(x) ] <- "first"
y
}
This works as intended, but I wonder whether there is a more efficient solution.