ifelse()
Using ifelse(), you can make a new variable based on the test you made.
>library(ggplot2)
> summary(diamonds$carat) -------------carat: size of carat in each diamond
Min. 1st Qu. Median Mean 3rd Qu. Max. 0.2000 0.4000 0.7000 0.7979 1.0400 5.0100
<EXAMPLE 1>
<new variable 'carattt' ------"small","big">
To make a new variable 'carattt' which consists of small and big, I will use a test in ifelse()
1st test: diamonds$carat<=0.7 |
Yes "small" |
|
No "big" |
> diamonds$carattt<-ifelse(diamonds$carat<=0.7,"small","big")
> table(diamonds$carattt)
big small
26778 27162
<Make a graph using a new variable 'carattt'>
> carattt_price<-diamonds%>%group_by(carattt)%>%summarise(mean_price=mean(price))
> ggplot(data=carattt_price,aes(x=carattt,y=mean_price))+geom_col()
<EXAMPLE 2>
<new variable 'caratt' ------"small","middle","big">
To make a new variable "caratt" which consists of small, middle and big, I will use two tests in ifelse().
1st test: diamonds$carat <=0.4 |
Yes "small" |
|
|
|
|
No |
2nd test: diamonds$carat<=1.04 |
Yes "middle" |
|
|
|
|
No |
"big" |
> diamonds$caratt<-ifelse(diamonds$carat<=0.4,"small",ifelse(diamonds$carat<=1.04,"middle","big"))
> table(diamonds$caratt)
big middle small
13379 26170 14391
<Make a graph using a new variable 'caratt'>
> caratt_price<-diamonds%>%group_by(caratt)%>%summarise(mean_price=mean(price))
> ggplot(data=caratt_price,aes(x=caratt,y=mean_price))+geom_col()
'R' 카테고리의 다른 글
(R) [dplyr] Rearrange data in order / arrange() / arrange(desc()) (0) | 2020.07.26 |
---|---|
(R) Fill,Color columns based on a variable/aes(x=,y=,fill=)/geom_col(position="dodge") (0) | 2020.07.24 |
(R) make a summary - group_by(),summarise() (0) | 2020.07.22 |
R reorder() -reorder columns in ascending order, descending order when setting aes() (0) | 2020.07.21 |
(R) geom_col() VS geom_bar() (0) | 2020.07.20 |