This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
#1 loop that calculates 12!
#initialize a variable var
var <- 12
# start loop
for(i in 11:1) {# loop goes from 11 to 1 decrements of 1
var <- var *i
}
# print results
var
## [1] 479001600
#2 create numeric vector that contains the sequence from 20 to 50 by 5
my_seq <- seq(from = 20, to = 50, by = 5)
my_seq
## [1] 20 25 30 35 40 45 50
#3 Create a function "quadratic" that takes in 3 inputs and solve the quadratic equation
quadratic <- function (a, b, c){ #creates function that takes in 3 inputs
discriminant <- b ^ 2 - 4 * a * c
# if discriminant is negative, then the solution is a complex number
if (discriminant < 0) {
# taking the absolute value of the discriminant then multiplying i
solution1 <- (-b + sqrt(abs(discriminant)) * 1i) / (2 * a)
solution2 <- (-b - sqrt(abs(discriminant)) * 1i) / (2 * a)
return(c(solution1, solution2))
} else { # runs this when the discriminant is a non negative number
solution1 <- (-b + sqrt(discriminant)) / (2 * a)
solution2 <- (-b - sqrt(discriminant)) / (2 * a)
return(c(solution1, solution2)) # returns the two solutions as a vector
}
}
quadratic(-7, 2, 9) # real solution
## [1] -1.000000 1.285714
quadratic(1, 0, 25) # complex solution
## [1] 0+5i 0-5i