Select nth element in data frame by factor

前端 未结 3 1768
迷失自我
迷失自我 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 22:55

    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]
    

提交回复
热议问题