How to sort a data frame in R

前端 未结 3 1787
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 14:03

I am new to R, and want to sort a data frame called \"weights\". Here are the details:

>str(weights)
\'data.frame\':   57 obs. of  1 variable:
 $ attr_imp         


        
相关标签:
3条回答
  • 2020-11-28 14:23

    Here is the big comparison on data.frame sorting:

    How to sort a dataframe by column(s)?

    Using my now-preferred solution arrange:

    dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), 
          levels = c("Low", "Med", "Hi"), ordered = TRUE),
          x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
          z = c(1, 1, 1, 2))
    library(plyr)
    arrange(dd,desc(z),b)
        b x y z
    1 Low C 9 2
    2 Med D 3 1
    3  Hi A 8 1
    4  Hi A 9 1
    
    0 讨论(0)
  • 2020-11-28 14:34

    Since your data.frame only has one column, you need to set drop=FALSE to prevent the dimensions from being dropped:

    weights[order(-weights$attr_importance),,drop=FALSE]
    #         attr_importance
    # our         0.125433292
    # all         0.098185517
    # address     0.090686474
    # over        0.075182467
    # make        0.049630556
    # num3d       0.007122618
    
    0 讨论(0)
  • 2020-11-28 14:40

    rankdata.txt

    regno   name           total    maths   science social cat
    1   SUKUMARAN   400 78  89  73  S
    2   SHYAMALA    432 65  79  87  S
    3   MANOJ       500 90  129 78  C
    4   MILYPAULOSE 383 59  88  65  G
    5   ANSAL       278 39  77  60  O
    6   HAZEENA     273 45  55  56  O
    7   MANJUSHA    374 50  99  52  C
    8   BILBU       408 81  97  72  S
    9   JOSEPHROBIN 374 57  85  68  G
    10  SHINY       381 70  79  70  S
    z <- data.frame(rankdata)
    
    z[with(z, order(-total+ maths)),]  #order function  maths group selection
    z
    z[with(z, order(name)),]  # sort on name
    z
    
    0 讨论(0)
提交回复
热议问题