Sort based on Frequency in R

半世苍凉 提交于 2021-01-01 07:15:57

问题


Structure of input dataframe

ds= structure(list(MSISDN = c(800, 800, 783, 
975, 800)), .Names = "Number", row.names = c(NA, 
-5L), class = "data.frame")

Need a simple output which looks like below (not able to add single break)

Num Freq

800 3

975 1

783 1


回答1:


Check out Tabyl function from janitor package. It does the task that you want plus a bit more

library(janitor)
    ds <- structure(list(MSISDN = c(800, 800, 783,975, 800)), .Names = "Number", row.names = c(NA,-5L), class = "data.frame")

    tabyl(ds$Number)



回答2:


This should work.

Base

df <- data.frame(table(xx$Number))
df[rev(order(df$Freq)),]

Result

  #    Var1 Freq
  #    800    3
  #    975    1
  #    783    1

You can sort using dplyr as well.

library(dplyr)
df %>% arrange(desc(Freq))

Data

xx <- structure(list(MSISDN = c(800, 800, 783, 
975, 800)), .Names = "Number", row.names = c(NA, 
-5L), class = "data.frame")



回答3:


using only dplyr

xx %>% group_by(Number) %>% summarise(Freq=n()) %>% arrange(desc(Freq))


来源:https://stackoverflow.com/questions/49883606/sort-based-on-frequency-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!