You can find my solutions for the exercises of BDA 503 - Week 1
Write a function to convert Fahrenheit to Celsius and Celsius to Fahrenheit.
(X°C × 9/5) + 32 = Y°F
convert_temperature <- function(degree,F_to_C){
if (F_to_C == TRUE){
new_degree <- (degree - 32) * (5/9)
}
else{
new_degree <- degree * (9/5) + 32
}
return(new_degree)
}
convert_temperature(30,F_to_C = FALSE)
## [1] 86
convert_temperature(86,F_to_C = TRUE)
## [1] 30
Write a function to calculate the future value of an investment given annually compounding interest over an amount of years.
calculate_future_value <- function(investment,interest,duration_in_years){
future_value <- investment * (1 + interest)^duration_in_years
return(future_value)
}
calculate_future_value(
investment = 100, interest = 0.07, duration_in_years = 5)
## [1] 140.2552
Write a function to randomly generate n color hex codes. You can use letters predefined vector.
generate_hex_code <- function(n){
letters= c("a","b","c","d","f")
numbers= 1:9
pool= c(letters,numbers)
hexcodes = c()
for (i in 1:n) {
hex_values <- sample(pool,6)
hex_code <- paste0(hex_values[1],hex_values[2],hex_values[3],hex_values[4],hex_values[5],hex_values[6])
hexcodes = c(hexcodes,hex_code)
}
return(hexcodes)
}
generate_hex_code(n=3)
## [1] "63c12f" "dc8f32" "bc415a"
Write a function which calculates the probability of getting k sixes in n throws of a die. Hint: Use binomial distribution.
get_prob_dice <- function(k,n){
prob <-dbinom(k,n, prob = 1/6)
return(prob)
}
get_prob_dice(3,5)
## [1] 0.03215021
Write a rock scissors paper game which computer randomly chooses
rsp_game <- function(rsp){
rsp <- tolower(rsp)
chocies <- c("rock","paper","scissors")
comp_selects <- sample(chocies,1)
if (rsp == comp_selects){
response <- "I chose the same. Tie!"
} else if(rsp == "rock" && comp_selects == "paper"){
response <- "I chose paper. I won"
} else if(rsp == "rock" && comp_selects == "scissors"){
response <- "I chose scissors. You won"
} else if(rsp == "paper" && comp_selects == "rock"){
response <- "I chose rock. You won"
} else if(rsp == "paper" && comp_selects == "scissors"){
response <- "I chose scissors. I won"
} else if(rsp == "scissors" && comp_selects == "paper"){
response <- "I chose paper. You won"
} else if(rsp == "scissors" && comp_selects == "rock"){
response <- "I chose rock. I won"
} else{
response <- "I didn't understand you Hoo-man. Please write rock or scissors or paper."
}
return(response)
}
rsp_game("rock")
## [1] "I chose scissors. You won"