Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 5 topmost values from vector in R?

Tags:

r

vector

topmost

I have a vector and I'm able to return highest and lowest value, but how to return 5 topmost values? Is there a simple one-line solution for this?

like image 480
pixel Avatar asked Sep 11 '10 20:09

pixel


People also ask

How do you get top 5 values in R?

To get the top values in an R data frame, we can use the head function and if we want the values in decreasing order then sort function will be required. Therefore, we need to use the combination of head and sort function to find the top values in decreasing order.

How do you show the highest value in R?

Max() function in R For this, we first create a vector and then apply the max() function, which returns the max value in the vector.

How do I select a value from a vector in R?

The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.


2 Answers

x[order(x)[1:5]] 
like image 41
hadley Avatar answered Sep 25 '22 22:09

hadley


> a <- c(1:100) > tail(sort(a),5) [1]  96  97  98  99 100 
like image 115
chrisamiller Avatar answered Sep 22 '22 22:09

chrisamiller