我想按降序创建以下标志向量。即空单元表示最高,M表示最低。所以min("",E)应该给E.我应该如何在R中做到这一点?
flag= c(" ", "T", "I", "E", "M")
答案 0 :(得分:0)
在R中没有直接的方法。我建议将矢量重新编码为整数。
如果真的想要做这样的事情你可以通过以下方式来定义你自己的类并使用因子而不是字符向量:
# Create your vector as a factor, so that you can assign an order
flag <- factor(c(" ", "T", "I", "E", "M"))
# Define the order of the levels (= unique values) of your factor
levels(flag) <- c("M", "E", "I", "T", " ")
# assign a custom class to your factor so that you can write a min() method for it
class(flag) <- c("my_flag", class(flag))
# write a min function for your my_flag class
min.my_flag <- function(x, na.rm = FALSE){
if(na.rm) x <- na.omit(x)
x[which.min(as.integer(x))]
}
min(flag)