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
<- function(number){
squareOfNumber <- number^2
squareNumber return(squareNumber)
}
squareOfNumber(3)
## [1] 9
– Create a function which takes two numbers and returns the mean
<- function(number,number2){
meanOfNumbers <- mean(c(number,number2))
meanOfNumbersRes return(meanOfNumbersRes)
}
meanOfNumbers(1,3)
## [1] 2
<- function(vector,vector2){
meanOfVectors <- mean(c(vector,vector2))
meanOfVectorsRes return(meanOfVectorsRes)
}
meanOfVectors(1,3)
## [1] 2
<- function(number,number2){
dfAndVecReturn <- c(number,number2)
input <- data.frame(mean=mean(c(number,number2)),
df 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.
<- function(x){
findSmallestFactorial <- 0
factorialAnswer <- 0
count while(factorialAnswer <= x){
<- count+1
count if(count == 1){
<- 1
factorialAnswer else{
}<- factorialAnswer * count
factorialAnswer
}
}return(count)
}
findSmallestFactorial(3000)
## [1] 7
findSmallestFactorial(10^100)
## [1] 70
– Add a if and else statement in your function to only calculate factorial code if argument is a numeric.
<- function(x){
findSmallestFactorial if(!is.numeric(x)){
message("Please provide a numeric argument!")
else{
}<- 0
factorialAnswer <- 0
count while(factorialAnswer <= x){
<- count+1
count if(count == 1){
<- 1
factorialAnswer else{
}<- factorialAnswer * count
factorialAnswer
}
}return(count)
}
}
findSmallestFactorial(3000)
## [1] 7
findSmallestFactorial("Hello")
## Please provide a numeric argument!