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

Vas*_*a B 4 r

我有x作为

x <- c("7", "2", "3", "8", "8")
Run Code Online (Sandbox Code Playgroud)

我想要输出

[1] "2" "3" "8"
Run Code Online (Sandbox Code Playgroud)

并删除8和7中的一个.因此删除最大的两个数字之一.

Ric*_*ven 10

这是一种可能性match().

x[-match(tail(sort(unique(x)), 2), x)]
# [1] "2" "3" "8"
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,作为唯一的选择,可以扩展到2个以上的删除. (3认同)

Vee*_*kar 6

另一个选择使用 which.max

x[-c(which.max(x), match(max(x[x != max(x)]), x))]    
#[1] 2 3 8
Run Code Online (Sandbox Code Playgroud)


mr.*_*don 5

有很多方法可以实现这一目标.我认为矢量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
Run Code Online (Sandbox Code Playgroud)