Teja Teja - 1 year ago 79
R Question

How to get top n companies from a data frame in decreasing order

I am trying to get the top 'n' companies from a data frame.Here is my code below.

data("Forbes2000", package = "HSAUR")

Now I would like to get the top 50 observations from this sorted vector.

Answer Source

head and tail are really useful functions!

head(sort(Forbes2000$profits,decreasing=TRUE), n = 50)

If you want the first 50 rows of the data.frame, then you can use the arrange function from plyr to sort the data.frame and then use head


head(arrange(Forbes2000,desc(profits)), n = 50)

Notice that I wrapped profits in a call to desc which means it will sort in decreasing order.

To work without plyr

head(Forbes2000[order(Forbes2000$profits, decreasing= T),], n = 50)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download