R 从向量中删除两个最大的唯一数字

R 从向量中删除两个最大的唯一数字,r,R,我有xas x <- c("7", "2", "3", "8", "8") 然后拆下8和7中的一个。因此,删除两个最大数字中的一个。有许多方法可以实现这一点。我认为向量x应该转换为数值,但这是可行的 x <- (c('7','2','3','8','8')) # read in data remove <- tail(unique(x[order(x)]),2) # take the unique elements and sort, identifying the las

我有
x
as

x <- c("7", "2", "3", "8", "8")

然后拆下8和7中的一个。因此,删除两个最大数字中的一个。

有许多方法可以实现这一点。我认为向量x应该转换为数值,但这是可行的

x <- (c('7','2','3','8','8')) # read in data
remove <- tail(unique(x[order(x)]),2)  # take the unique elements and sort, identifying the last 2
x[ - c(which(x==remove[1])[1], which(x==remove[2])[1])  ] #remove only the one of each of the two found

x这里有一个可能性是
match()


另一个选项使用
which.max

x[-c(which.max(x), match(max(x[x != max(x)]), x))]    
#[1] 2 3 8

这应该是公认的答案,因为这是扩展到2次以上清除的唯一选项。
x[-match(tail(sort(unique(x)), 2), x)]
# [1] "2" "3" "8"
x[-c(which.max(x), match(max(x[x != max(x)]), x))]    
#[1] 2 3 8