-4

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

2 Answers2

3

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)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Code is fine but this is not working if the location has only one site and the occurrence is only one ,i am getting NA for those – Sandeep Shetty Jun 21 '16 at 13:22
  • 1
    @SandeepShetty I tried with an example that mimics your situation, but I am not getting NAs (you can check the update) – akrun Jun 21 '16 at 18:11
2

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)
Tomas H
  • 713
  • 4
  • 10
  • Thanks,The code worked but i am seeing lot of new functions like arrange,slice etc,Can you please help me how can i learn more on dplyr package as i cant remember so many functions by heart – Sandeep Shetty Jun 21 '16 at 12:52
  • 1
    you can watch this two part video https://www.youtube.com/watch?v=jWjqLW-u3hc on dplyr and this is good tutorial video on tidyr and dplyr https://www.rstudio.com/resources/webinars/data-wrangling-with-r-and-rstudio/ – Tomas H Jun 21 '16 at 12:58
  • 1
    search for "dplyr cheatsheet" – Ben Bolker Jun 21 '16 at 12:58