Here we will discuss if, if else, and else if statements in R, and use them to create simple functions.
For other statement types for creating algorithms, see the pages on for loop and while loop statements, and creating functions.
If, if else, and else if statements perform one of a set of possible tasks based on what condition is satisfied.
The if else statement can be extended to multiple layers with else if:
if(condition){
task code chunk
} else if(new condition){
first alternative task code chunk
} else{
second alternative task code chunk
}
This can continue with as many conditions and alternative statements as possible, provided they are well defined.
You can use logical and relational operators to specify conditions.
[1] 1
[1] "We need more."
[1] "Retry!"
a = 12
if(a < 5){
print("We need more.")
} else if(a < 10){
print("We might need more.")
} else{
print("We have enough.")
}
[1] "We have enough."
The cube of a number \(y\) is \(y^3\).
The argument of interest is \(y>0\).
To create the function, use:
For \(y=2\):
[1] 8
To allow for custom error statement when \(y<0\), update to:
cubeP = function(y){
if(y > 0){
cube = y^3
} else {cube = "Error: this is a negative number."}
return(cube)
}
You can then evaluate for the numbers \(y=4\) and \(y=-6\):
[1] 64
[1] "Error: this is a negative number."
A quadratic equation is of the form:
\[ax^2 + bx + c = 0\]
with \(a\ne0\), and \(a, \; b, \; c \;\) as integers.
The two roots or solutions are:
\[x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}\]
The discriminant is \(D = b^2 - 4ac\).
For \(D > 0\), the equation has real and distinct roots.
For \(D = 0\), the equation has real and equal roots.
For \(D < 0\), the equation does not have real roots.
The arguments of interest are \(a\), \(b\) and \(c\).
To create the function to find the roots, use:
rootq = function(a, b, c){
D = b^2 - 4*a*c
if(D > 0){
root1 = (-b - sqrt(b^2 - 4*a*c))/(2*a)
root2 = (-b + sqrt(b^2 - 4*a*c))/(2*a)
roots = c(root1, root2)
} else if(D == 0){
roots = paste("Equal roots:", -b/(2*a))
} else {roots = "Real roots do not exist."}
return(roots)
}
You can then derive the roots for \((a, b, c) = (1, 1, -6) , (1, 4, 4) \; \text{and} \; (1, 2, 8)\), that is \(x^2 + x - 6 = 0\), \(x^2 + 4x + 4 = 0\), and \(x^2 + 2x + 8 = 0\) respectively:
[1] -3 2
[1] "Equal roots: -2"
[1] "Real roots do not exist."
The feedback form is a Google form but it does not collect any personal information.
Please click on the link below to go to the Google form.
Thank You!
Go to Feedback Form
Copyright © 2020 - 2024. All Rights Reserved by Stats Codes