R Programming
- Overview of R
- Installing R on Windows
- Download and Install RStudio on Windows
- Setting Your Working Directory (Windows)
- Getting Help with R
- Installing R Packages
- Loading R Packages
- Take Input and Print in R
- R Objects and Attributes
- R Data Structures
- R – Operators
- Vectorization
- Dates and Times
- Data Summary
- Reading and Writing Data to and from R
- Control Structure
- Loop Functions
- Functions
- Data Frames and dplyr Package
- Generating Random Numbers
- Random Number Seed in R
- Random Sampling
- Data Visualization Using R
If-else condition in R
if Statement in R:
The if-else combination is probably the most commonly used control structure not only in R but also for other programming languages. This structure allows you to test a condition and act on it depending on whether it’s true or false.
if statement in R:
The syntax of if statement is:
if (condition) {
#R Code
}
x<-200
if(x > 100){
print("X is greater than 100")
}
Output:
[1] "X is greater than 100"
If the condition is TRUE, the statement gets executed. But if it’s FALSE, nothing happens. Here, condition can be a logical or numeric vector, but only the first element is taken into consideration.
You could have a series of if clauses that always get executed if their respective conditions are true.
if(condition1) {
R Code
}
if(condition2) {
R Code
}
if…else statement in R:
In R, the if/else syntax is:
if (condition) {
R code
} else {
R code
}
if-else:
x <- readline(prompt="Enter a number: ") #Take input from user. Then run the next line.
y <- if(x > 10){
print("Value is greater than 10")
} else {
print("Value is less than or equal to 10")
}
Output:
> x <- readline(prompt="Enter a number: ")
Enter a number: 11
[1] "Value is more than 10"
Example:
x = 4
y = 6
if (x > y) {
print("x is larger than y")
} else {
print("x is less than or equal to y")
}
Output:
[1] "x is less than or equal to y"
ifelse() Function in R:
This is called Vectorization with ifelse. The ifelse() function is a vector equivalent form of the if…else statement in R. This vectorization of code, will be much faster than applying the same function to each element of the vector individually.
So, you can use if-else like this also
ifelse(4 > 3, "greater","less")
Output:
[1] "greater"
This is how we use ifelse() to a vector.
x<- 1:20
ifelse(x> 10, "greater", "less")
Output:
[1] "less" "less" "less" "less" "less" "less" "less" "less" "less" "less" "greater" "greater"
[13] "greater" "greater" "greater" "greater" "greater" "greater" "greater" "greater"
Nested if…else statement in R:
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
Output:
[1] "Zero"