Remove the two largest unique numbers from the vector

I have xboth

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

I need a conclusion

[1] "2" "3" "8"

and delete one of 8 and 7. Therefore, delete one of the largest two numbers.

+4
source share
3 answers

There are many ways to achieve this. I think that the vector x should be dropped to numeric, but this works.

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
+5
source

Here is the opportunity with match().

x[-match(tail(sort(unique(x)), 2), x)]
# [1] "2" "3" "8"
+10
source

Another option using which.max

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

Source: https://habr.com/ru/post/1616002/


All Articles