Select nth element in data frame by factor

前端 未结 3 1765
迷失自我
迷失自我 2021-01-21 22:29

I\'ve got a dataframe with a text column name and factor city. It is ordered alphabetically firstly by city and then name. No

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 23:06

    You can use plyr for this:

    dat <- structure(list(name = c("John", "Josh", "Matt", "Bob", "Kate", 
    

    "Lily", "Matt"), city = c("Atlanta", "Atlanta", "Atlanta", "Boston", "Boston", "Boston", "Boston")), .Names = c("name", "city"), class = "data.frame", row.names = c(NA, -7L))

    library(plyr)
    
    ddply(dat, .(city), function(x, n) x[n,], n=3)
    
    > ddply(dat, .(city), function(x, n) x[n,], n=3)
      name    city
    1 Matt Atlanta
    2 Lily  Boston
    > ddply(dat, .(city), function(x, n) x[n,], n=4)
      name   city
    1    
    2 Matt Boston
    > 
    

    There are plenty of other options too using base R or data.table or sqldf...

提交回复
热议问题