Functions, solutions
Source:vignettes/functions_exercises_solutions.Rmd
functions_exercises_solutions.Rmd
- Write a function that divides two numbers. If the divider is zero, it shouldn’t try the division, but give a message about it.
my_first_function <- function(num1, num2){
if (num2==0){
stop("Not working")
}
res <- num1/num2
return(res)
}
- Write a function that changes all vowels of a string to e-s.
esperente <- function(c){
gsub("[aoiu]", "e", c)
}
- Add a checking part, that checks if the input is indeed one character and it has vowels in it. If not, it should give a message.
esperente <- function(c){
if (!is.character(c)){
message("Not a character")
}
if (length(c)!=1){
message("Too many elements!")
}
if (!grepl("[aoiu]", c)){
message("The result will be the same!")
}
gsub("[aoiu]", "e", c)
}
- Write a function that calculates the variance of a vector.
\[Var(x)=\frac 1{n-1}\sum_{i=1}^{n} (x_{i}-\overline{x})^2\] where \[\overline{x}=\frac{\sum_{i=1}^{n}x_{i}}n\]
- Add code to check if the input data is in the correct format.
variance <- function(num){
if (!is.numeric(num))
stop("The input can only be numeric.")
if (length(num)<2){
message("Calculating the variance only makes sense with more than two numbers!")
}
sum((num-mean(num))^2)/(length(num)-1)
}
- Add a warning, if the class of the input vector is not numeric, and try to coerce as one.
variance <- function(num){
if (!is.numeric(num))
num <- as.numeric(num)
warning("The input can only be numeric, tried to coerce as one.")
if (length(num)<2){
message("Calculating the variance only makes sense with more than two numbers!")
}
sum((num-mean(num))^2)/(length(num)-1)
}