What does function mean in Rstudio?

Functions are useful when you want to perform a certain task multiple times. A function accepts input arguments and produces the output by executing valid R commands that are inside the function. In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and you can have one or more function definitions in a single R file.

  • Built-in Function: Built function R is sq(), mean(), max(), these function are directly call in the program by users.
  • User-defined Function: R language allow us to write our own function.

Functions are created in R by using the command function(). The general structure of the function file is as follows: 



Note: In the above syntax f is the function name, this means that you are creating a function with name f which takes certain arguments and executes the following statements.

Built-in Function in R Programming Language

Here we will use built-in function like sum(), max() and min().

Output:

[1] 15 [1] 6 [1] 4

User-defined Functions in R Programming Language

R provides built-in functions like print(), cat(), etc. but we can also create our own functions. These functions are called user-defined functions.

Example:  

Output: 

[1] "even" [1] "odd"

Single Input Single Output

Now create a function in R that will take a single input and gives us a single output. 

Following is an example to create a function that calculates the area of a circle which takes in the arguments the radius. So, to create a function, name the function as “areaOfCircle” and the arguments that are needed to be passed are the “radius” of the circle.  

areaOfCircle = function(radius){

Output: 

12.56637

Multiple Input Multiple Output

Now create a function in R Language that will take multiple inputs and gives us multiple outputs using a list. 

The functions in R Language takes multiple input objects but returned only one object as output, this is, however, not a limitation because you can create lists of all the outputs which you want to create and once the list is created you can access them into the elements of the list and get the answers which you want.

Let us consider this example to create a function “Rectangle” which takes “length” and “width” of the rectangle and returns area and perimeter of that rectangle. Since R Language can return only one object. Hence, create one object which is a list that contains “area” and “perimeter” and return the list. 

Rectangle = function(length, width){

  perimeter = 2 * (length + width)

  result = list("Area" = area, "Perimeter" = perimeter)

resultList = Rectangle(2, 3)

print(resultList["Area"])

print(resultList["Perimeter"])

Output: 

$Area [1] 6 $Perimeter [1] 10

Inline Functions in R Programming Language

Sometimes creating an R script file, loading it, executing it is a lot of work when you want to just create a very small function. So, what we can do in this kind of situation is an inline function.

To create an inline function you have to use the function command with the argument x and then the expression of the function. 

Example: 

f = function(x) x^2*4+x/3

Output: 

65.33333 15.33333 0

Passing arguments to Functions in R Programming Language

There are several ways you can pass the arguments to the function: 

  • Case 1: Generally in R, the arguments are passed to the function in the same order as in the function definition.
  • Case 2: If you do not want to follow any order what you can do is you can pass the arguments using the names of the arguments in any order.
  • Case 3: If the arguments are not passed the default values are used to execute the function.

Now, let us see the examples for each of these cases in the following R code:

Rectangle = function(length=5, width=4){

print(Rectangle(width = 8, length = 4))

Output: 

6 32 20

Lazy evaluations of Functions in R Programming Language

In R the functions are executed in a lazy fashion. When we say lazy what it means is if some arguments are missing the function is still executed as long as the execution does not involve those arguments.

Example: 

In the function “Cylinder” given below. There are defined three-argument “diameter”, “length” and “radius” in the function and the volume calculation does not involve this argument “radius” in this calculation. Now, when you pass this argument “diameter” and “length” even though you are not passing this “radius” the function will still execute because this radius is not used in the calculations inside the function. 
Let’s illustrate this in an R code given below:

Cylinder = function(diameter, length, radius ){

  volume = pi*diameter^2*length/4

Output: 

196.3495

If you do not pass the argument and then use it in the definition of the function it will throw an error that this “radius” is not passed and it is being used in the function definition.

Example: 

Cylinder = function(diameter, length, radius ){

  volume = pi*diameter^2*length/4

Output: 

Error in print(radius) : argument "radius" is missing, with no default

Article Tags :

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

To create a function, use the function() keyword:

my_function <- function() { # create a function with the name my_function  print("Hello World!")

}

Call a Function

To call a function, use the function name followed by parenthesis, like my_function():

my_function <- function() {  print("Hello World!")}

my_function() # call the function named my_function

Try it Yourself »

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

my_function <- function(fname) {  paste(fname, "Griffin")}my_function("Peter")my_function("Lois")

my_function("Stewie")

Try it Yourself »

The terms "parameter" and "argument" can be used for the same thing: information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less:

This function expects 2 arguments, and gets 2 arguments:

my_function <- function(fname, lname) {  paste(fname, lname) }

my_function("Peter", "Griffin")

Try it Yourself »

If you try to call the function with 1 or 3 arguments, you will get an error:

This function expects 2 arguments, and gets 1 argument:

my_function <- function(fname, lname) {  paste(fname, lname) }

my_function("Peter")

Try it Yourself »

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without an argument, it uses the default value:

my_function <- function(country = "Norway") {  paste("I am from", country)}my_function("Sweden")my_function("India") my_function() # will get the default value, which is Norway

my_function("USA")

Try it Yourself »

Return Values

To let a function return a result, use the return() function:

my_function <- function(x) {  return (5 * x)} print(my_function(3))print(my_function(5))

print(my_function(9))

Try it Yourself »

The output of the code above will be:

[1] 15 [1] 25

[1] 45

Nested Functions

There are two ways to create a nested function:

  • Call a function within another function.
  • Write a function within a function.

Call a function within another function:

Nested_function <- function(x, y) {  a <- x + y  return(a) }

Nested_function(Nested_function(2,2), Nested_function(3,3))

Try it Yourself »

Example Explained

The function tells x to add y.

The first input Nested_function(2,2) is "x" of the main function.

The second input Nested_function(3,3) is "y" of the main function.

The output is therefore (2+2) + (3+3) = 10.

Write a function within a function:

Outer_func <- function(x) {  Inner_func <- function(y) {    a <- x + y    return(a)  }  return (Inner_func)}output <- Outer_func(3) # To call the Outer_func

output(5)

Try it Yourself »

Example Explained

You cannot directly call the function because the Inner_func has been defined (nested) inside the Outer_func.

We need to call Outer_func first in order to call Inner_func as a second step.

We need to create a new variable called output and give it a value, which is 3 here.

We then print the output with the desired value of "y", which in this case is 5.

The output is therefore 8 (3 + 5).

Recursion

R also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly, recursion can be a very efficient and mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.

tri_recursion <- function(k) {  if (k > 0) {    result <- k + tri_recursion(k - 1)    print(result)  } else {    result = 0    return(result)  }}

tri_recursion(6)

Try it Yourself »



Última postagem

Tag