The R programming language allows the user to create their own new functions. In this tutorial you will learn**how to write a function in r**, what the syntax is, the arguments, the output, how the callback function works, and how to make proper use of optional, additional, and default arguments.

- 1 How to write a function in the R language? Definition of R functions
- 1.1 Creating a function in R

- 2 Input arguments in R functions
- 3 standard arguments for functions in R
- 4 Additional Arguments in R
- 5 The return function R
- 6 Local and Global Variables in R
- 7 Writing a function in R. Examples
- 7.1 Example of function 1: Spanish DNI letter
- 7.2 Example of function 2: Throwing a die

## How to write a function in R language? Definition of R functions

The basic functions of R don't always cover all our needs. To write a function in R first**I need to know how the syntax works**do`Occupation`

the command is. The basic syntax of the R function is as follows:

`function_name <- function(arg1, arg2, ... ) { # Code}`

In the code block above we have the following parts:

`arg1, arg2, ...`

they are the**input arguments**.`# code`

represents the**code to run**inside the function to calculate the desired output.

Him**The output of the function can be**a number, a list, a data frame, a frame, a message, or**any object you want**. You can also assign some class to the output, but we'll talk about that in another post with S3 classes. The latter is especially interesting when writing functions for R packages.

### Create a function in R

To introduce R functions, let's create a function to work with geometric progressions. A geometric progression is a sequence of numbers.a_1, a_2, a_3such that each of them (except the first) is equal to the last one multiplied by a constant*r*called reason. You can check this,

a_2 = a_1 \cdot r; \qquad a_3 = a_2 \cdot r = a_1 \cdot r^2; \pontos

Therefore, generalizing this process, we can obtain the general term

a_n = a_1 \cdot r^{n-1}.

You can also verify that the sum of*norte*terms of the progression is

S_n = a_1 + \dots + a_n = \frac{a_1(r^n - 1)}{r-1}.

With that in mind, you can create the following function,

`a <- function(a1, r, n){ a1 * r ** (n - 1)}`

which computes the general termeof a geometric progression giving the parametersa_1, the radio*r*and the value*norte*. In the next block we can see some examples with their outputs as comments.

`an(a1 = 1, r = 2, n = 5) # 16an(a1 = 4, r = -2, n = 6) # -128`

With the above function you can get multiple values from the progression by passing a vector of values to the argument*norte*.

`an(a1 = 1, r = 2, n = 1:5) # a_1, ..., a_5an(a1 = 1, r = 2, n = 10:15) # a_10,..., a_15`

You can also calculate the first*norte*progression elements with`sn`

function, defined below.

`sn <- função(a1, r, n){ a1 * (r ** n-1)/(r - 1)}`

`sn(a1 = 1, r = 2, n = 5) # 31# Equivalent values <- an(a1 = 1, r = 2, n = 1:5)value(values) # 31`

## Input arguments in R functions

**Arguments are input values of functions.**. As an example, in the function we created earlier, we have three input arguments called`a1`

,`r`

y`norte`

. There are several considerations when dealing with these types of arguments:

- If you
**keep the order of entry**, you guys**no need to call argument names**. As an example, the following calls are equivalent.

`an(1, 2, 5) # Returns 16an(a1 = 1, r = 2, n = 5) # Returns 16`

- If you
**name the arguments**, You can use**any order**.

`an(r = 2, n = 5, a1 = 1) # Returns 16an(n = 5, r = 2, a1 = 1) # Returns 16`

- You can make use of
`arguments`

it works**know the input arguments of any function**you would like to use.

`arguments (a)`

- If you
**calling function name**, the console will return the**function code**.

**keep in mind that**sometimes you won't be able to see the source code of a function if it's not written in R.

## Default arguments for functions in R

Sometimes it's really interesting to have default function arguments, so the**default values will be used unless others are added**when executing the function. When writing a function, like the one in our example,

`function_name <- function(arg1, arg2, arg3) {#Code}`

if you want`arg2`

y`arg3`

to be`an`

y`b`

by default you can assign them in the arguments of your R function.

`function_name <- function(arg1, arg2 = a, arg3 = b) { #Code}`

Let's illustrate this with a very simple example. Consider, for example, a function that graphs cosine.

`cosine <- function ( w = 1 , min = -2 * pi , max = 2 * pi ) { x <- seq ( -2 * pi , 2 * pi , longitude = 200 ) graph ( x , cos ( w * x ), digit = "l")}`

Note that this is not the best way to use a function to graph. Consult the S3 classes for this purpose.

if you run`cosine()`

the plot of`because(x)`

will be plotted by default in the interval [-2 π , 2 π ]. However, if you want to plot the function`because (2x)`

in the same range you need to run`coseno (w = 2)`

. Let's look at some examples:

`# One row, three columnseven(mfcol = c(1, 3))cos()cos(w = 2)cos(w = 3, min = -3 * pi)`

## Additional arguments in R

the argument`...`

(dot-dot-dot) allows you to freely pass arguments that will be used by a subfunction within the main function. For example, in the function,

`coseno <- function(w = 1, min = -2 * pi, max = 2 * pi, ...) { x <- seq(-2 * pi, 2 * pi, length = 200) plot(x, cos (w * x), ...)}`

the arguments inside`...`

will be used by`plot`

Occupation. Let's look at a complete example:

`par(mfcol = c(1, 2))coseno(w = 2, col = "rojo", tipo = "l", lwd = 2)coseno(w = 2, ylab = "")`

## The return function of R

By default, R functions will return the last object evaluated within it. You can also make use of`return`

function, which is especially important when you want to return one or another object depending on certain conditions, or when you want to run some code after the object you want to return. It's worth noting that you can return all types of R objects, but only one. That's why it's very common to return a list of objects, as follows:

`asn <- function(a1 = 1, r = 2, n = 5) { A <- an(a1, r, n) S <- sn(a1, r, n) ii <- 1:n AA <- an (a1, r, ii) SS <- sn(a1, r, ii) return(list(an = A, sn = S, output = data.frame(values = AA, sum = SS)))}`

When you run the function, you will get the following output. Remember to have the`sn`

y`e`

functions loaded into the workspace.

`asn()`

`$`an`[1] 16$sn[1] 31$output values sum1 1 12 2 33 4 74 8 155 16 31`

You may have noticed that in the previous case it is equivalent to using the`return`

work or not use it. However, consider the following example, where we want to check whether the parameters passed to the arguments are numbers or not. To do this, if any of the parameters is not a number, we will return a string, but if they are numbers, the code will continue executing.

`asn <- function(a1 = 1, r = 2, n = 5) { if(!is.numeric(c(a1, r, n))) return("Os parâmetros devem ser números") A <- an( ; a1 , r , n ) S < - sn ( a1 , r , n ) ii < - 1 : n AA < - an ( a1 , r , ii ) SS <- sn ( a1 , r , ii ) return ( lista ( an . ); = A, sn = S, output = data.frame(values = AA, sum = SS)))}`

`asn("3")`

`"Parameters must be numbers"`

If we used the`print`

function instead of`return`

, when any parameter is not numerical, the text will be returned, but also an error, as all the code will be executed.

`asn <- function(a1 = 1, r = 2, n = 5) { if(!is.numeric(c(a1, r, n))) print("Os parâmetros devem ser números") A <- an( a1 , r , n ) S < - sn ( a1 , r , n ) ii < - 1 : n AA <- an ( a1 , r , ii ) SS <- sn ( a1 , r , ii ) return ( lista ( uma = A, sn = S, output = data.frame(values = AA, sum = SS)))}`

`asn("3")`

`"Parameters must be numbers" Error in a1 * r^(n - 1): non-numeric argument to binary operator`

## Local and global variables in R

In R it is not necessary to declare the variables used inside a function. The rule called “lexicographic scope” is used to decide whether an object is local to a function or global. Consider, for example, the following example:

`fun <- function() { print(x)}x<- 1fun() # 1`

the variable`x`

is not defined inside`fun`

, then R will look for`x`

inside the "around" scope and print its value. Yes`x`

is used as the name of an object within the function, the value of`x`

in the global environment (outside of the function) does not change.

`x <- 1fun2 <- function() { x <- 2 print(x)}fun2() # 2x #1`

To change the global value of a variable within a function, you can use the double assignment operator (`<<-`

).

`x <- 1y <- 3fun3 <- function() { x <- 2 y <<- 5 print(paste(x, y))}fun3() # 2 5x # 1 (the value has not changed)y # 5 ( value changed)`

## Writing a function in R. Examples

This section shows different examples of R functions to illustrate creating and using R functions.

### Function example 1: Spanish DNI letter

Let's calculate the DNI letter from its corresponding number. The method used to obtain the letter (L) of the DNI consists of dividing the number by 23 and according to the remainder (R) obtained, assigning the corresponding letter to the following table.

R | eu | R | eu | R | eu | R | eu | |||
---|---|---|---|---|---|---|---|---|---|---|

0 | T | 7 | F | 14 | Z | 21 | k | |||

1 | R | 8 | PAG | 15 | S | 22 | mi | |||

2 | C | 9 | D | sixteen | q | |||||

3 | AN | 10 | x | 17 | V | |||||

4 | GRAMS | 11 | B | 18 | H | |||||

5 | METRO | 12 | norte | 19 | eu | |||||

6 | Y | 13 | j | 20 | C |

The function will be as follows.

`ID <- function(number) { letters <- c("T", "R", "W", "A", "G", "M", "Y", "F", "P", D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K" , "E") letters <- letters[number %% 23 + 1] return(letters)}`

`DNI(50247828)#G`

### Function example 2: Throw a die

The following function simulates*norte*(by default*n = 100*) throws of the dice. The function returns the frequency table and the corresponding graph.

`dice <- function(n = 100){ throws <- sample(1:6, n, rep = T) frecuencia <- table(throws)/n barplot(frequency, main = "") abline(h = 1/6 , col = 'rojo', lwd = 2) retorno (frequência)}`

Now you can see the simulation results by running the function.

`par(mfcol = c(1, 3))say(100)say(500)say(100000)`

`# 100 1 2 3 4 5 60,17 0,11 0,20 0,16 0,25 0,11# 500 1 2 3 4 5 60.144 0,158 0,148 0,178 0,164 0,208# 100000 1 2 3 4 5 60.16612 0,166630 0,16569 0,16791`

As you can see, as we increase*norte*we are closer to the theoretical value 1/6 = 0.1667.

## FAQs

### How do you create a function in R example? ›

**R Functions**

- Creating a Function. To create a function, use the function() keyword: Example. ...
- Call a Function. To call a function, use the function name followed by parenthesis, like my_function(): Example. ...
- Default Parameter Value. The following example shows how to use a default parameter value.

**What is the syntax to write a custom function in R? ›**

The basic syntax for a custom R function is **FunctionName = function(Argument(s)) {Statement(s)}** . All functions are assigned a name FunctionName; they end up as objects in your workspace, and are implemented by name. Argument(s) represented the input data objects, which can range for one to several.

**How do you create a function syntax? ›**

Arguments typically have some restrictions on the expression used for that argument. For example, **the input argument to the INDEX function can only be an object name**. Depending on the function, one or many data objects can be used for an input argument for one function evaluation.

**Which of the following examples is the proper syntax for a function in R? ›**

3. Which of the following examples is the proper syntax for calling a function in R? Correct: An example of the syntax for a function in R is **print()**. If you add an argument in the parentheses for the print() function, the argument will appear in the console pane of RStudio.

**How do you give a function example? ›**

An example of a simple function is **f(x) = x ^{2}**. In this function, the function f(x) takes the value of “x” and then squares it. For instance, if x = 3, then f(3) = 9. A few more examples of functions are: f(x) = sin x, f(x) = x

^{2}+ 3, f(x) = 1/x, f(x) = 2x + 3, etc.

**What is function () in R? ›**

What Is a Function in R? A function in R is **an object containing multiple interrelated statements that are run together in a predefined order every time the function is called**. Functions in R can be built-in or created by the user (user-defined).

**What Is syntax to create function with example? ›**

Syntax to create a function:

**CREATE [OR REPLACE] FUNCTION function_name [parameters]** **[(parameter_name [IN | OUT | IN OUT] type [, ...])]** **RETURN return_datatype**.

**What is the syntax of R? ›**

R Command Prompt

**> myString <- "Hello, World!" > print ( myString) [1] "Hello, World!"** Here first statement defines a string variable myString, where we assign a string "Hello, World!" and then next statement print() is being used to print the value stored in variable myString.

**What is the syntax list in R programming? ›**

Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using **list() function**.

**Which is a basic syntax for a function? ›**

In order to work correctly, a function must be written a specific way, which is called the syntax. The basic syntax for a function is **an equals sign (=), the function name (SUM, for example), and one or more arguments**.

### WHAT IS function and write its syntax? ›

Functions allow to structure programs in segments of code to perform individual tasks. In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is: **type name ( parameter1, parameter2, ...)** **{ statements }**

**What is the syntax of some function? ›**

The syntax of a function in Excel or Google Sheets refers to **the layout and order of the function and its arguments**. A function in Excel and Google Sheets is a built-in formula. All functions begin with the equal sign ( = ) followed by the function's name such as IF, SUM, COUNT, or ROUND.

**What is the correct syntax for IF function *? ›**

Syntax. Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: **=IF(A2>B2,"Over Budget","OK")**

**What are various functions in R programming explain with examples? ›**

Operator | Description |
---|---|

abs(x) | Takes the absolute value of x |

log(x,base=y) | Takes the logarithm of x with base y; if base is not specified, returns the natural logarithm |

exp(x) | Returns the exponential of x |

sqrt(x) | Returns the square root of x |

**What are the data structures in R explain with syntax and example? ›**

R's basic data structures include the **vector, list, matrix, data frame, and factors**. Some of these structures require that all members be of the same data type (e.g. vectors, matrices) while others permit multiple data types (e.g. lists, data frames). Objects may have attributes, such as name, dimension, and class.

**What are the 4 types of functions? ›**

**There are 4 types of functions:**

- Functions with arguments and return values. This function has arguments and returns a value: ...
- Functions with arguments and without return values. ...
- Functions without arguments and with return values. ...
- Functions without arguments and without return values.

**What is a simple function example? ›**

A basic example of a simple function is **the floor function over the half-open interval [1, 9), whose only values are {1, 2, 3, 4, 5, 6, 7, 8}**. A more advanced example is the Dirichlet function over the real line, which takes the value 1 if x is rational and 0 otherwise.

**What are the 2 types of functions give examples? ›**

For example, f ( x ) = 3 x + 7 is a **polynomial function**. A Quadratic function is a kind of function that holds the highest power two in the polynomial function. For example, f ( x ) = x 2 − 4 is a quadratic function.

**How many types of functions are in R? ›**

Similar to the other languages, R also has **two** types of function, i.e. Built-in Function and User-defined Function.

**How do I apply a function in R? ›**

The R base manual tells you that it's called as follows: **apply(X, MARGIN, FUN, ...)** where: X is an array or a matrix if the dimension of the array is 2; MARGIN is a variable defining how the function is applied: when MARGIN=1 , it applies over rows, whereas with MARGIN=2 , it works over columns.

### What is the syntax example? ›

Syntax in English sets forth a specific order for grammatical elements like subjects, verbs, direct and indirect objects, etc. For example, if a sentence has a verb, direct object, and subject, the proper order is **subject → verb → direct object**.

**What is stored function write the syntax to create a function? ›**

A stored function is **a set of SQL statements that perform some operation and return a single value**. Just like Mysql in-built function, it can be called from within a Mysql statement. By default, the stored function is associated with the default database.

**What is RM () function in R? ›**

The rm() code **removes objects in your workspace**. You can begin your code with the rm() function to clear all of the objects from your workspace to start with a clean environment.

**Is R syntax hard? ›**

R is known for being hard to learn. This is in large part because R is so different from many programming languages. **The syntax of R, unlike languages like Python, is very difficult to read**. Basic operations like selecting, naming, and renaming variables are more confusing in R than they are in other languages.

**How do I write code in R? ›**

To start writing a new R script in RStudio, **click File – New File – R Script**. Shortcut! To create a new script in R, you can also use the command–shift–N shortcut on Mac.

**What is code syntax? ›**

Syntax is **the set of rules that define what the various combinations of symbols mean**. This tells the computer how to read the code. Syntax refers to a concept in writing code dealing with a very specific set of words and a very specific order to those words when we give the computer instructions.

**What are types of syntax in programming? ›**

To simplify understanding and analyzing a language's syntax, we separate syntax into three levels: **lexical elements, context free syntax, and context sensitive syntax**.

**What is names () function in R? ›**

The names() function in R is **used to get or set the name of an object**. The object can be a list, vector, matrix, and DataFrame. Use names(x) to get the name of the object and names(x) <- vector to assign names to the object. To remove the object name assign the value NULL .

**What is the simplest programming syntax? ›**

**HTML, which stands for HyperText Markup Language**, is one of the most common programming languages for beginners, as it's often seen as the most straightforward programming language to learn.

**What Is syntax give answer? ›**

Syntax is **the grammar, structure, or order of the elements in a language statement**. (Semantics is the meaning of these elements.) Syntax applies to computer languages as well as to natural languages.

### What is IF statement syntax and example? ›

**if (score >= 90) grade = 'A';** The following example displays Number is positive if the value of number is greater than or equal to 0 . If the value of number is less than 0 , it displays Number is negative .

**What is the syntax for IF function identify the 3 arguments of the function? ›**

IF is one of the Logical functions in Microsoft Excel, and there are 3 parts (arguments) to the IF function syntax: logical_test: TEST something, such as the value in a cell. value_if_true: Specify what should happen if the test result is TRUE. value_if_false: Specify what should happen if the test result is FALSE.

**How do you write an if and function? ›**

AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)

**How many functions are there in R language? ›**

**19** Functions | R for Data Science.

**What is a structure explain structure with syntax and example? ›**

A structure is **a collection of variables of same or different datatypes**. It is useful in storing or using informations or databases. Example: An employee's record must show its salary, position, experience, etc. It all can be stored in one single variable using structures.

**What is the function used to sort the data in R explain the syntax? ›**

There is a function in R that you can use (called the **sort function**) to sort your data in either ascending or descending order. The variable by which sort you can be a numeric, string or factor variable. You also have some options on how missing values will be handled: they can be listed first, last or removed.

**What is syntax in data structure? ›**

Syntax refers to **the rules that define the structure of a language**. Syntax in computer programming means the rules that control the structure of the symbols, punctuation, and words of a programming language. Without syntax, the meaning or semantics of a language is nearly impossible to understand.

**What is function in R with example? ›**

In R, a function is **an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions**. The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects.

**How do I step into a function in R? ›**

**The function debug()** in R allows the user to step through the execution of a function, line by line. At any point, we can print out values of variables or produce a graph of the results within the function. While debugging, we can simply type “c” to continue to the end of the current section of code.

**How do I create a function for a DataFrame in R? ›**

**1.**

**Create a DataFrame in R using data.**

**frame()**

- The input objects passed to data. frame() should have the same number of rows.
- The column names should be non-empty.
- Duplicate column names are allowed, but you need to use check. names = FALSE .
- You can assign names to rows using row. ...
- Character variables passed to data.

### How do you make a formula in R? ›

R can be used as a powerful calculator by entering equations directly at the prompt in the command console. Simply **type your arithmetic expression and press ENTER**. R will evaluate the expressions and respond with the result.

**WHAT IS function and its example? ›**

A function is **a kind of rule that, for one input, it gives you one output**. An example of this would be y=x2. If you put in anything for x, you get one output for y. We would say that y is a function of x since x is the input value.

**What are the types of function explain with example? ›**

Based on Elements | One One Function Many One Function Onto Function One One and Onto Function Into Function Constant Function |
---|---|

Based on Equation | Identity Function Linear Function Quadratic Function Cubic Function Polynomial Functions |

**How do you identify a function in R? ›**

The function “identify()” will allow you to determine which record correspond to a particular data point on the graph, simply by clicking on it. In order to do that, we first need to **call the graph (with the plot function for example), and then call the “identify()” function**.

**How do I apply a function to a column in R? ›**

apply() lets you perform a function across a data frame's rows or columns. In the arguments, you specify what you want as follows: **apply(X = data.** **frame, MARGIN = 1, FUN = function.**

**How do I view functions in R? ›**

...

**In RStudio, there are (at least) 3 ways:**

- Press the F2 key while cursor is on any function.
- Click on the function name while holding Ctrl or Command.
- View (function_name) (as stated above)

**What does the data frame () function do in R? ›**

The function data. frame() **creates data frames, tightly coupled collections of variables which share many of the properties of matrices and of lists**, used as the fundamental data structure by most of R's modeling software.

**How do you add a function to a Dataframe? ›**

**Pandas dataframe.append() function** is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value.

**How do you create a Dataframe in a function? ›**

To create a dataframe, we need to import pandas. **Dataframe can be created using dataframe() function**. The dataframe() takes one or two parameters. The first one is the data which is to be filled in the dataframe table.

**How do you create a formula? ›**

**Create a formula that refers to values in other cells**

- Select a cell.
- Type the equal sign =. Note: Formulas in Excel always begin with the equal sign.
- Select a cell or type its address in the selected cell.
- Enter an operator. ...
- Select the next cell, or type its address in the selected cell.
- Press Enter.

### How do you create a basic formula? ›

Simple formulas **always start with an equal sign (=), followed by constants that are numeric values and calculation operators such as plus (+), minus (-), asterisk(*), or forward slash (/) signs**.