r - How to find the nth lowest value without sorting -
i have data set values multiple cities in each state. third (for example) lowest value in each state, , return name of city.
i can lowest value in each state with:
tapply(df2[,11],df2$state, min )
but how nth lowest (and return city name)?
data in column 11, state in column 7 (with header "state"), city name in column 2.
try example:
#dummy data df <- data.frame( state=paste0("state",sort(rep(1:2,10))), city=rep(paste0("city",rep(1:10,2))), value=runif(n=20)) #get rank per state df$rank <- ave(df$value, df$state, fun = rank) #subset 3rd lowest per state df[df$rank==3,]
edit:
as pointed out arun, partial sort solution, using data.table
package:
library(data.table) dt <- data.table(df) dt[dt[, .i[value == sort(value, partial=3l)[3l]], by=state]$v1]
Comments
Post a Comment