So i have an example of dataframe below:
Index Country
4.1 USA
2.1 USA
5.2 USA
1.1 Singapore
6.2 Singapore
8.1 Germany
4.5 Italy
7.1 Italy
2.3 Italy
5.9 Italy
8.8 Russia
And, I intend to get the N elements for each group of Country in the dataframe. For example, if N = 3, then I will take 3 rows from each group, and if any particular group doesn't have N elements like Singapore, then it will just take what is sufficient which is the two records with Country label Singapore. The same applies for Country label with more than N elements such as Italy, hence it will just take three of it.
For N = 3, the output dataframe would be:
Index Country
4.1 USA
2.1 USA
5.2 USA
1.1 Singapore
6.2 Singapore
8.1 Germany
4.5 Italy
7.1 Italy
2.3 Italy
8.8 Russia
I was thinking of something like:
aggregate(df, by=list(df$Country), head(df, 3))
But it doesn't seemed to work.