I have the data frame like
now i need to get the output with most frequently occurred levels like
Could any one help me on this please??
I have the data frame like
now i need to get the output with most frequently occurred levels like
Could any one help me on this please??
We can use Mode
function from here
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
and use it in any of the group by functions. One option is with dplyr
library(dplyr)
df %>%
group_by(location) %>%
summarise(site = Mode(site))
# location site
# <chr> <chr>
#1 a site
#2 b bang
#3 c site
Or with base R
with(df, tapply(as.character(site), location, FUN = Mode))
df<-data.frame(location=rep(letters[1:3], c(3, 1, 2)),
site = c("site", "site", "bang", "bang", "site", "bang"), stringsAsFactors=FALSE)
You can do something like this with dplyr
set.seed(43)
df<-data.frame(location=sample(LETTERS[1:3],20,replace=TRUE),
site=sample(c("bang","mys","hubl","dar"),20,replace=TRUE))
library(dplyr)
df%>%group_by(location,site)%>%summarize(Count=n())%>%arrange(desc(Count))%>%slice(1)%>%ungroup()%>%select(location,site)