I\'ve got a dataframe with a text column name
and factor city
. It is ordered alphabetically firstly by city
and then name
. No
A data.table
solution
library(data.table)
DT <- data.table(test)
# return all columns from the subset data.table
n <- 4
DT[,.SD[n,] ,by = city]
## city name
## 1: Atlanta NA
## 2: Boston Matt
## 3: Seattle NA
# if you just want the nth element of `name`
# (excluding other columns that might be there)
# any of the following would work
DT[,.SD[n,] ,by = city, .SDcols = 'name']
DT[, .SD[n, list(name)], by = city]
DT[, list(name = name[n]), by = city]