How to select top 10 records while using the aggregate function in R

r
aggregation
data_wrangling

#1

Hello,

I am using the following code:

agg_sales_pcat <- aggregate(store_sales ~ product_category,data = agg_sales,mean)
to aggregate store sales product category wise.But there are 45 different product categories and I want only the top 10 records from agg_sales_pcat.
So is there a way to do this in aggregate or do i have to use separate line of code for this??


#2

@hackers, what exactly do you mean by top 10? Is it simply the first 10 rows or is there some other way of ordering? It would be helpful if could give us a sample of the dataset (or at least of the relevant columns) and the current agg_sales_pact.


#3

hello @anon,

My bad,i should have given this:

I want the top 10 by store_sales.


#4

In that case, you can simply sort agg_sales_pcat by sales and pick the first (or last, depending on the order) ten. In base R, you can use the order function and the subset the resulting dataframe.