First of all, in this particular case, the actual vector to order is:
values <- sapply(thresholds, function (t) t$value)
# values == c(100, 50, 100, 1, 50)
You can adjust the function inside sapply
for your needs (for instance, do the appropriate casting depending on whether you want to sort in numeric or alphabetical order, etc.).
From this point, if we were to keep the duplicates, the answer would simply be:
thresholds[order(values)]
order
returns for each element in "values" its rank, i.e. its position if the vector were sorted. Here order(values)
is 4 2 5 1 3
. Then, thresholds[order(values)]
returns the elements of thresholds
identified by these indices, producing 1 50 50 100 100
.
However, since we want to remove duplicates, it cannot be as simple as that. unique
won't work on thresholds
and if we apply it to values
, it will lose the correspondence with the indices in the original list.
The solution is to use another function, namely duplicated
. When applied on a vector, duplicated
returns a vector of booleans, indicating for each element, if it already exists in the vector at an earlier position. For instance, duplicated(values)
would return FALSE FALSE TRUE FALSE TRUE
. This vector is the filter on duplicated elements we need here.
The solution is therefore:
ordering <- order(values)
nodups <- ordering[!duplicated(values)]
thresholds[nodups]
or as a one-liner:
thresholds[order(values)[!duplicated(values)]]