RDPD
RDPD

Reputation: 565

How to retrieve the index values of first 5 in r?

I sorted a data set which is a vector and i want to retrieve the indices of the first five values in the vector.

I used the following code to sort data set and retrieve the first five values. But i am not sure how to retrieve its indices.

head(sort(dsq), 5)

Upvotes: 0

Views: 316

Answers (2)

fishtank
fishtank

Reputation: 3728

Maybe you want order which will return the indice of element that can be used to permute the sequence into ascending or descending order.

order(dsq)

Upvotes: 1

akrun
akrun

Reputation: 887108

We can use index.return=TRUE argument in the sort. It will return a list of length 2. From this, extract the index ($ix) and get the first 5 values with head.

head(sort(dsq, index.return=TRUE)$ix, 5)

Upvotes: 1

Related Questions