Chapter 12 Functions in R
Function is basically a set of statements intended to perform a specific task. For example, you may want to add three numbers just by entering three numbers. user defined function can be created using keyword ‘function’.
12.1 Inbuilt functions in R
R has inbuilt functions such as R,
12.2 Custom Function Creation
Let’s create a function addition that can add three numbers. Functions have arguments, which are a kind of placeholder. Let’s say we want to create a function that can add three numbers. While writing this function we need to pass argument to the function. In following case, i have passed arguments as a,b and c.
addition<- function(a,b,c) {
a+b+c
}
Use function ‘addition’ to add three numbers 1,2,3
addition(1,2,3)
## [1] 6
Let’s create a function to convert Fahrenheit to degree Celsius. General expression to convert Fahrenheit to celsius is Celsius,c =(5/9)*(Fahrenheit-32) The function takes Fahrenheit as input and returns output in degree Celsius
DegreeToFahrenheit<- function(F) {
(5/9)*(F-32)
}
we have just created a function to change Degree to Fahrenheit. We can call the function and pass an argument. Here argument is the temperature in Fahrenheit
DegreeToFahrenheit(100)
## [1] 37.77778
12.3 Function without Argument
We can also call a function without an argument for example, lets ce
12.4 Create a function without an argument.
cube_of_n <- function() {
for(x in 1:3) {
print(x^3)
}
}
Here cube of n will print the cube of first n numbers: -
cube_of_n()
## [1] 1
## [1] 8
## [1] 27