>library(ggplot2)
>library(dplyr)
> the_number_of_each_manu<-mpg%>%group_by(manufacturer)%>%summarise(n=n())
> the_number_of_each_manu
# A tibble: 15 x 2
manufacturer n
<chr> <int>
1 audi 18
2 chevrolet 19
3 dodge 37
4 ford 25
5 honda 9
6 hyundai 14
7 jeep 8
8 land rover 4
9 lincoln 3
10 mercury 4
11 nissan 13
12 pontiac 5
13 subaru 14
14 toyota 34
15 volkswagen 27
arrange()-order in the smallest to the largest
> the_number_of_each_manu<-mpg%>%group_by(manufacturer)%>%summarise(n=n())%>%arrange(n)
> the_number_of_each_manu
# A tibble: 15 x 2
manufacturer n
<chr> <int>
1 lincoln 3
2 land rover 4
3 mercury 4
4 pontiac 5
5 jeep 8
6 honda 9
7 nissan 13
8 hyundai 14
9 subaru 14
10 audi 18
11 chevrolet 19
12 ford 25
13 volkswagen 27
14 toyota 34
15 dodge 37
arrange(desc())-order in the largest to the smallest
> the_number_of_each_manu<-mpg%>%group_by(manufacturer)%>%summarise(n=n())%>%arrange(desc(n))
> the_number_of_each_manu
# A tibble: 15 x 2
manufacturer n
<chr> <int>
1 dodge 37
2 toyota 34
3 volkswagen 27
4 ford 25
5 chevrolet 19
6 audi 18
7 hyundai 14
8 subaru 14
9 nissan 13
10 honda 9
11 jeep 8
12 pontiac 5
13 land rover 4
14 mercury 4
15 lincoln 3
application-arrange(n)
> bottom_5<-mpg%>%group_by(manufacturer)%>%summarise(n=n())%>%arrange(n)%>%head(5)
> bottom_5
# A tibble: 5 x 2
manufacturer n
<chr> <int>
1 lincoln 3
2 land rover 4
3 mercury 4
4 pontiac 5
5 jeep 8
> ggplot(data=bottom_5,aes(x=manufacturer,y=n))+geom_col()
If you need the explanation of reordering columns please click the link below.
[R] - R reorder() -reorder columns in ascending order, descending order
> ggplot(data=bottom_5,aes(x=reorder(manufacturer,n),y=n))+geom_col()
> ggplot(data=bottom_5,aes(x=reorder(manufacturer,-n),y=n))+geom_col()
application-arrange(desc(n))
> top_5<-mpg%>%group_by(manufacturer)%>%summarise(n=n())%>%arrange(desc(n))%>%head(5)
> top_5
# A tibble: 5 x 2
manufacturer n
<chr> <int>
1 dodge 37
2 toyota 34
3 volkswagen 27
4 ford 25
5 chevrolet 19
> ggplot(data=top_5,aes(x=manufacturer,y=n))+geom_col()
> ggplot(data=top_5,aes(x=reorder(manufacturer,n),y=n))+geom_col()
> ggplot(data=top_5,aes(x=reorder(manufacturer,-n),y=n))+geom_col()
'R' 카테고리의 다른 글
(R) count the number of elements/ count() (0) | 2020.07.29 |
---|---|
(R)Make a new variable/ mutate() (0) | 2020.07.27 |
(R) Fill,Color columns based on a variable/aes(x=,y=,fill=)/geom_col(position="dodge") (0) | 2020.07.24 |
(R) ifelse() (0) | 2020.07.23 |
(R) make a summary - group_by(),summarise() (0) | 2020.07.22 |