'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
Solution 1:[1]
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")
Solution 2:[2]
using only dplyr
xx %>% group_by(Number) %>% summarise(Freq=n()) %>% arrange(desc(Freq))
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rana Usman |
| Solution 2 | user2797174 |
| Solution 3 | GKi |
