0

I am looking for the most common Start Station Name in the column. So I used:

Top_Start_Station_Name <- df %>%
  count(start_station_name)

However, it contains 82 pages of station names and their occurrences. How can I arrange it to have the most 5 station names appear?

Rfanatic
  • 2,224
  • 1
  • 5
  • 21
tu le
  • 3
  • 2
  • 1
    You can arrange by using exactly this dplyr word… `arrange`. – deschen Dec 08 '21 at 05:49
  • You want to count the number of times that each station name occurs and then return the names of the five most common? – rg255 Dec 08 '21 at 05:58
  • Yes rg255, Sorry for any confusing. – tu le Dec 08 '21 at 06:01
  • 1
    Maybe try `count(start_station_name, sort=TRUE) %>% slice(1:5)`. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Dec 08 '21 at 06:07
  • Thank you MrFlick. It does work now. Really appreciate. – tu le Dec 08 '21 at 06:09

2 Answers2

0

Try this: This should give you a plot of the top 5 stations:

library(tidyverse)
df %>% 
  mutate(start_station_name = fct_lump(start_station_name, n=5)) %>% 
  count(start_station_name) %>% 
  mutate(start_station_name = fct_reorder(start_station_name, n)) %>% 
  ggplot(aes(start_station_name, n))+
  geom_col()+
  coord_flip()
TarJae
  • 72,363
  • 6
  • 19
  • 66
0

the arrange(desc(.)) function composition can sort by counts (named n) in the tbl_df that results from the count function:

 Top_5_Start_Station_Names <- df %>% 
                          count(start_station_name) %>% # 2 col tbl, first col are names
                          arrange(desc(n)) %>% 
                          .[1:5,1]    # pick first 5 items from first col

If you wanted both the names and counts you could use .[1:5 ] as the last function. (Only now do I see the more compact and earlier comment by @MrFlick.)

IRTFM
  • 258,963
  • 21
  • 364
  • 487