These exercises are about the functions sections of Introduction to R.
– Create a function which takes one number and returns the square of that number
squareOfNumber <- function(number){
squareNumber <- number^2
return(squareNumber)
}
squareOfNumber(3)
## [1] 9
– Create a function which takes two numbers and returns the mean
meanOfNumbers <- function(number,number2){
meanOfNumbersRes <- mean(c(number,number2))
return(meanOfNumbersRes)
}
meanOfNumbers(1,3)
## [1] 2
meanOfVectors <- function(vector,vector2){
meanOfVectorsRes <- mean(c(vector,vector2))
return(meanOfVectorsRes)
}
meanOfVectors(1,3)
## [1] 2
dfAndVecReturn <- function(number,number2){
input <- c(number,number2)
df <- data.frame(mean=mean(c(number,number2)),
sum=number+number2,
multiple=number*number2
)
return(list(input,df))
}
dfAndVecReturn(1,3)
## [[1]]
## [1] 1 3
##
## [[2]]
## mean sum multiple
## 1 2 4 3
– Create a function which takes one argument and finds the smallest number whose factorial is greater than that argument.
findSmallestFactorial <- function(x){
factorialAnswer <- 0
count <- 0
while(factorialAnswer <= x){
count <- count+1
if(count == 1){
factorialAnswer <- 1
}else{
factorialAnswer <- factorialAnswer * count
}
}
return(count)
}
findSmallestFactorial(3000)
## [1] 7
## [1] 70
– Add a if and else statement in your function to only calculate factorial code if argument is a numeric.
findSmallestFactorial <- function(x){
if(!is.numeric(x)){
message("Please provide a numeric argument!")
}else{
factorialAnswer <- 0
count <- 0
while(factorialAnswer <= x){
count <- count+1
if(count == 1){
factorialAnswer <- 1
}else{
factorialAnswer <- factorialAnswer * count
}
}
return(count)
}
}
findSmallestFactorial(3000)
## [1] 7
## Please provide a numeric argument!