unique / sort in data.frame

后端 未结 3 1678
小蘑菇
小蘑菇 2021-01-17 14:21

I have a data frame like this:

x=c(\"01\",\"01\",\"01\",\"22\",\"22\",\"03\",\"03\",\"03\",\"35\",\"35\")
y=c(\"f\",\"f\",\"f\",\"m\",\"m\",\"m\",\"m\",\"m\"         


        
相关标签:
3条回答
  • 2021-01-17 14:31
    df2 = df[!duplicated(df), ] # Remove duplicated rows.
    df3 = df2[order(df2$spn), ] # Sort by the spn column.
    
    df3
    #  spn sex
    #1  01   f
    #6  03   m
    #4  22   m
    #9  35   f
    
    0 讨论(0)
  • 2021-01-17 14:42
    df <- df[order(df$spn), ]
    > df[!duplicated(df), ]
      spn sex
    1  01   f
    6  03   m
    4  22   m
    9  35   f
    
    0 讨论(0)
  • 2021-01-17 14:49

    Use unique then order:

    df <- unique(df)
    df[order(df$spn), ]
    

    Using dplyr, data.table:

    library(dplyr)
    unique(df) %>% arrange(spn)
    #   spn sex
    # 1  01   f
    # 2  03   m
    # 3  22   m
    # 4  35   f
    
    library(data.table)
    unique(setDT(df))[ order(spn), ]
    #    spn sex
    # 1:  01   f
    # 2:  03   m
    # 3:  22   m
    # 4:  35   f
    
    0 讨论(0)
提交回复
热议问题