Let’s consider a vector of numeric values “x”. Some values may be duplicates. I need to remove the max value one by one until x is empty.
Problem, if I use:
x <- x[x != max(x)]
It removes all duplicates equal to the maximum. I want to remove only one of the duplicates. So until now, I do:
max.x <- x[x == max(x)]
max.x <- max.x[1:length(max.x) - 1]
x <- c(x[x != max(x)], max.x)
But this is far from computationally efficient, and I’m not good enough at R to find the right way to do this. Can someone has a better trick?
Thanks
You’re not entirely clear what the scope of your problem is, so I’ll just give the first suggestion I have that comes to mind. Use the
sortfunction to get the list of values in decreasing order.sorted <- sort(x,decreasing=TRUE,index.return=TRUE)You can now iteratively remove the highest item from
x. Re-using thesortfunction over and over on your subset data is inefficient – better to keep a permanent copy ofxand do the removals from that, if possible.Consider this approach