1

R language : How to sort a vector and print Top X value when the value is flat ?

If I have a vector like

v <- c(1,2,3,3,4,5)

I want to print the TOP1~TOP3 values.

So I use:

sort(v)[1:3]
[1] 1 2 3

In this case,TOP3 have 2 value

what I want to print is:

[1] 1 2 3 3

and their index

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
破嘎獸
  • 35
  • 5

2 Answers2

3

One way to do it:

v[v %in% sort(v)[1:3]]
# [1] 1 2 3 3

# following up OP's comment, if you want ordered outcomes:
# sort(v[v %in% sort(v)[1:3]])
OzanStats
  • 2,756
  • 1
  • 13
  • 26
  • If v <- c(2,3,3,1,4,5) the result will be [1] 2 3 3 1 – 破嘎獸 Nov 30 '18 at 07:48
  • Then, you can sort it again: `sort(v[v %in% sort(v)[1:3]])` – OzanStats Nov 30 '18 at 07:56
  • You can take a look at [this post](https://stackoverflow.com/questions/5577727/is-there-an-r-function-for-finding-the-index-of-an-element-in-a-vector). Please make sure to clarify your questions so you don't need to iterate again and again with follow-ups. – OzanStats Nov 30 '18 at 08:14
2

We can use top_n from dplyr

library(dplyr)
data.frame(v) %>% top_n(-3)

#  v
#1 1
#2 2
#3 3
#4 3

this returns a dataframe, if you want a vector pull it

data.frame(v) %>% top_n(-3) %>% pull(v)
#[1] 1 2 3 3
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213