- 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_factorial <- function(arg_1) {
factorial = 1 #initialize
for(i in 1:arg_1)
factorial = factorial * i
print(factorial)
}
calculate_factorial(13)
## [1] 6227020800
calc_fac_while <-function(arg_1) {
factorial = 1 #initialize factorial
val = 1 #initialize loop count
while (val <= arg_1)
{
factorial = factorial * val
val = val + 1
}
print(factorial)
}
calc_fac_while(13)
## [1] 6227020800
- Show how to create a numeric vector that contains the sequence from 10 to 50 by 5.
num_vector <- c(10, 15, 20, 25, 30, 35, 40, 45, 50)
num_vector
## [1] 10 15 20 25 30 35 40 45 50
vec_by_five <-function(min, max) {
n = c() #create empty vector
num = 1 #initialize
while (num <= max)
{
if (num >= min)
if (num %% 5 == 0)
n <- append(n, num)
num = num + 1
}
print (n)
}
vec_by_five(10, 50)
## [1] 10 15 20 25 30 35 40 45 50
- 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(x1, x2, y1, y2){
distance <- sqrt((x2-x1)**2 + (y2-y1)**2)
slope <- (y2-y1) / (x2-x1)
b1 <- y1 - slope * x1
b2 <- y2 - slope*x2
print(distance)
print(slope)
print(b1)
print(b2) #just to confirm the y intercept is correct
}
lines(1, 4, 3, 7)
## [1] 5
## [1] 1.333333
## [1] 1.666667
## [1] 1.666667