Let's take a look at the use of the ifelse statement by performing the following steps:
- Create the variable x as a numeric object in R using the concatenation function c() as follows:
x <- c(13, 21, 19, 18, 21, 16, 21, 24, 17, 18, 12, 18, 29, 17,
18, 11, 13, 20, 25, 18, 15, 19, 21, 21, 7, 12, 23, 31, 16, 19,
23, 15, 25, 19, 15, 25, 25, 16, 29, 15, 26, 29, 23, 24, 20,
19, 14, 27, 22, 26)
- Now, calculate the cut-off value median as follows:
medX <- median(x)
medX # to see the value of median in R console
[1] 19
- Create the new variable newX using a conditional statement as follows:
newX <- ifelse(x>medX,1,0)
newX # Print the value of new variable into R console
[1] 0 1 0 0 1 0 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 1 1 0 0 1 1 0 0
1 0 1 0 0 1 1 0 1 0 1 1 1 1 1 0 0 1 1 1