This is Xhulia Turkaj’s R Markdown document for Week 1 Assignment on the R Bridge Course for CUNY SPS MSDS 2023.
Question 1
Write a loop that calculates 12-factorial.
factorial <- 1
for (i in 1:12) {
factorial <- factorial * i
}
print(paste("The factorial of 12 is:", factorial))
## [1] "The factorial of 12 is: 479001600"
Question 2
Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
my_vector <- seq(20,50, by=5)
my_vector
## [1] 20 25 30 35 40 45 50
Question 3
Create the function “quad” that takes a trio of input numbers a, b, and c and solve the quadratic equation. The function should print as output the two solutions. Please run and test your answer for (1,2,1), (1,6,5) and (1,1,1).
quad <- function(a, b, c) {
discriminant <- (b^2) - (4*a*c)
if(discriminant < 0) {
return(paste0("The quadratic equation has no real numbered solutions."))
}
else if(discriminant > 0) {
x_1 <- (-b + sqrt(discriminant)) / (2*a)
x_2 <- (-b - sqrt(discriminant)) / (2*a)
return(paste0("The two solutions for the quadratic equation are ",
x_1, " and ", x_2, "."))
}
else
x <- (-b) / (2*a)
return(paste0("The quadratic equation has only one solution, ",
x))
}
quad(1, 2, 1)
## [1] "The quadratic equation has only one solution, -1"
quad(1, 6, 5)
## [1] "The two solutions for the quadratic equation are -1 and -5."
quad(1, 1, 1)
## [1] "The quadratic equation has no real numbered solutions."