I’ve got a dataframe with a text column name and factor city. It is ordered alphabetically firstly by city and then name. Now I need to get a data frame which contains only nth element in each city, keeping this ordering. How can it be done in a pretty way without loops?
I have:
name city
John Atlanta
Josh Atlanta
Matt Atlanta
Bob Boston
Kate Boston
Lily Boston
Matt Boston
I want a function, which returns n’th element by city, i.e., if it is 3rd, then:
name city
Matt Atlanta
Lily Boston
It should return NULL for name if it is out of range for the selected city, i.e., for 4th:
name city
NULL Atlanta
Matt Boston
Using only base R please?
In base R using
by:Set up some test data, including an additional out of range value:
Get the 3rd item in each city:
Result:
To get exactly what you want, here is a little function:
Call it like:
Result: