본문 바로가기
R

(R) ifelse()

by jangpiano 2020. 7. 23.
반응형

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



반응형