1. Write a loop that calculates 13-factorial. Bonus - try to do it two different ways (for example use a for loop and a while loop). Do not use the standard factorial function. The goal is to learn about how R uses loops.
#calculate 13! with a for loop
result1 <-1
for (x in 1:13) {
result1 <- result1*x
}
#calculate 13! with a while loop
result2 <- 1
step <- 1
while (step <= 13) {
result2 <- result2*step
step <- step + 1
}
#show results
result1
## [1] 6227020800
result2
## [1] 6227020800
2. Show how to create a numeric vector that contains the sequence from 10 to 50 by 5.
#create vector with the c() function
vector1 <- c(10,15,20,25,30,35,40,45,50)
#create vector with the : operator
vector2 <- 2:10
vector2 <- vector2*5
#create vector with the seq() function
vector3 <- seq(10, 50, by=5)
#show vectors
vector1
## [1] 10 15 20 25 30 35 40 45 50
vector2
## [1] 10 15 20 25 30 35 40 45 50
vector3
## [1] 10 15 20 25 30 35 40 45 50
3. Create the function “lines” that takes two x,y points and calculates three things: the distance between those two points, the slope and the y intercept. The function should allow you to input both x and y values and give you the three answers.
lines <- function(point1x, point1y, point2x, point2y) {
#calculate the distance between two points
distance <- sqrt((point1x-point2x)^2+(point1y-point2y)^2)
#calculate the slope of two points
slope <- (point2y-point1y)/(point2x-point1x)
#calculate the y intercept of two point
yIntercept <- point1y - slope*point1x
#show results
print(sprintf("The points are: (%s,%s) and (%s,%s)", point1x, point1y, point2x, point2y))
print(sprintf("The distance between is: %s", distance))
print(sprintf("The slope is: %s", slope))
print(sprintf("The y-intercept is: %s", yIntercept))
}
lines(2,1,6,4)
## [1] "The points are: (2,1) and (6,4)"
## [1] "The distance between is: 5"
## [1] "The slope is: 0.75"
## [1] "The y-intercept is: -0.5"