Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

r - To get the most frequent levels in a data frame

I have the data frame like

enter image description here

now i need to get the output with most frequently occurred levels like

enter image description here

Could any one help me on this please??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

data

 df<-data.frame(location=rep(letters[1:3], c(3, 1, 2)),
     site = c("site", "site", "bang", "bang", "site", "bang"), stringsAsFactors=FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...