Question 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.

While loop solution:

f <- 13 #factorial
i <- f #loop count
s <- 1 #sum

while (i > 0){
  s <- s * i
  i <- i - 1
}
print(paste0("The factorial ", f,"! is: ", s))
## [1] "The factorial 13! is: 6227020800"

For loop solution:

f <- 13 #factorial
s <- 1 #sum

for (i in 1:f){ #loop count
  s <- s * i
}
print(paste0("The factorial ", f,"! is: ", s))
## [1] "The factorial 13! is: 6227020800"

Question 2

Show how to create a numeric vector that contains the sequence from 10 to 50 by 5.

Sequenced Vectors:

n <- seq(from = 10, to = 50, by =5) #vector numbers

print(n)
## [1] 10 15 20 25 30 35 40 45 50

Question 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.

Sequenced Vectors:

lines <- function(x1,x2,y1,y2){
  #distance
  d <- sqrt( ((x2-x1)^2) + ((y2-y1)^2) )
  #slope
  m <- (y2-y1)/(x2-x1)
  #y-intercept
  b <- -(m*x1) + y1
  cat("The distance between (", x1,",", y1,") and (", x2,",", y2,") is", d, "\n")
  cat("The slope of the line between (", x1,",", y1,") and (", x2,",", y2,") is", m, "\n")
  cat("The y-intercept between (", x1,",", y1,") and (", x2,",", y2,") is", b, "\n")
}
lines(4,3,6,3)
## The distance between ( 4 , 6 ) and ( 3 , 3 ) is 3.162278 
## The slope of the line between ( 4 , 6 ) and ( 3 , 3 ) is 3 
## The y-intercept between ( 4 , 6 ) and ( 3 , 3 ) is -6