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

mynum <- 13
mynum_fac <- 1
while (mynum>1) {
  mynum_fac <- mynum*mynum_fac
  mynum <- mynum-1
}
print(paste0("13! is: ",mynum_fac))
## [1] "13! is: 6227020800"

For Loop

mynum <- 13
mynum_fac <- 1
for(i in 1:mynum){
  mynum_fac <- mynum_fac*i
}
print(paste0("The factorial of ", mynum," is ",mynum_fac))
## [1] "The factorial of 13 is 6227020800"

Question 2

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

num_vec <- seq(10,50,5)
print(num_vec)
## [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 three answers.

lines <- function(x1,y1,x2,y2) {
    x <- (x1-x2)^2
    y <- (y1-y2)^2
    dist_btwn <- sqrt(x+y)
    slope <- (y2-y1)/(x2-x1)
    mx <- slope*x1
    y <- y1-mx
    b <- y
    cat("The distance between the points is: ",dist_btwn,"\n",
                 "The slope of the line is: ", slope,"\n", 
                  "The y intercept is: ",b,sep = "")
}
lines(1,2,2,3)
## The distance between the points is: 1.414214
## The slope of the line is: 1
## The y intercept is: 1