Sort data frame column by factor

后端 未结 4 2656
自闭症患者
自闭症患者 2020-12-06 00:43

Supose I have a data frame with 3 columns (name, y, sex) where name is character, y is a numeric value and <

4条回答
  •  悲哀的现实
    2020-12-06 01:29

    Here is a summary of all methods mentioned in other answers/comments (to serve future searchers). I've added a data.table way of sorting.

    # Base R
    do.call(rbind, by(score, score$sex, function(x) x[order(x$y),]))
    with(score, score[order(sex, y, x),])
    score[order(score$sex,score$x),]
    
    # Using plyr
    arrange(score, sex,y)
    ddply(score, c('sex', 'y'))
    
    # Using `data.table`
    library("data.table")
    score_dt <- setDT(score)
    
    # setting a key works sorts the data.table
    setkey(score_dt,sex,x)
    print(score_dt)
    

    Here is Another question that deals with the same

提交回复
热议问题