Vaibhav Singh
Vaibhav Singh

Reputation: 1209

Sort based on Frequency in R

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

Upvotes: 3

Views: 7308

Answers (4)

GKi
GKi

Reputation: 39657

Use table to get the frequencies, sort it in decreasing order and make with this a data.frame.

table(ds$Number) |> sort(TRUE) |> data.frame()  #Using pipes (since 4.1.0)
#data.frame(sort(table(ds$Number), TRUE))       #Traditional way
#  Var1 Freq
#1  800    3
#2  783    1
#3  975    1

Upvotes: 1

user12052711
user12052711

Reputation:

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)

Upvotes: 1

user2797174
user2797174

Reputation: 167

using only dplyr

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

Upvotes: 1

Rana Usman
Rana Usman

Reputation: 1051

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")

Upvotes: 3

Related Questions