Create FUNCTIONS in R ▷ [SYNTAX and EXAMPLES] (2023)

The R programming language allows the user to create their own new functions. In this tutorial you will learnhow 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 firstI need to know how the syntax worksdoOccupationthe 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 theinput arguments.
  • # coderepresents thecode to runinside the function to calculate the desired output.

HimThe output of the function can bea number, a list, a data frame, a frame, a message, orany 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 constantrcalled 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

(Video) How to Write Functions in R - Introduction to R Programming - Part 11

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

You can also verify that the sum ofnorteterms 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 radiorand the valuenorte. 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 argumentnorte.

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 firstnorteprogression elements withsnfunction, 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 calleda1,rynorte. There are several considerations when dealing with these types of arguments:

(Video) R Programming Tutorial - Learn the Basics of Statistical Computing

  • If youkeep the order of entry, you guysno 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 youname the arguments, You can useany order.
an(r = 2, n = 5, a1 = 1) # Returns 16an(n = 5, r = 2, a1 = 1) # Returns 16
  • You can make use ofargumentsit worksknow the input arguments of any functionyou would like to use.
arguments (a)
  • If youcalling function name, the console will return thefunction code.

keep in mind thatsometimes 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 thedefault values ​​will be used unless others are addedwhen executing the function. When writing a function, like the one in our example,

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

if you wantarg2yarg3to beanybby 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 runcosine()the plot ofbecause(x)will be plotted by default in the interval [-2 π , 2 π ]. However, if you want to plot the functionbecause (2x)in the same range you need to runcoseno (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)
Create FUNCTIONS in R ▷ [SYNTAX and EXAMPLES] (1)
(Video) R Programming for Beginners | Complete Tutorial | R & RStudio

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 byplotOccupation. 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 = "")
Create FUNCTIONS in R ▷ [SYNTAX and EXAMPLES] (2)

The return function of R

By default, R functions will return the last object evaluated within it. You can also make use ofreturnfunction, 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 thesnyefunctions 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 thereturnwork 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 theprintfunction instead ofreturn, 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:

(Video) For Loops in R

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

the variablexis not defined insidefun, then R will look forxinside the "around" scope and print its value. Yesxis used as the name of an object within the function, the value ofxin 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.

ReuReuReuReu
0T7F14Z21k
1R8PAG15S22mi
2C9Dsixteenq
3AN10x17V
4GRAMS11B18H
5METRO12norte19eu
6Y13j20C

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 simulatesnorte(by defaultn = 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
Create FUNCTIONS in R ▷ [SYNTAX and EXAMPLES] (3)
(Video) Write a function in MATLAB

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

FAQs

How do you create a function in R example? ›

R Functions
  1. Creating a Function. To create a function, use the function() keyword: Example. ...
  2. Call a Function. To call a function, use the function name followed by parenthesis, like my_function(): Example. ...
  3. 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) = x2. 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) = x2 + 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? ›

Math functions
OperatorDescription
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
1 more row
Jan 21, 2023

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()
  1. The input objects passed to data. frame() should have the same number of rows.
  2. The column names should be non-empty.
  3. Duplicate column names are allowed, but you need to use check. names = FALSE .
  4. You can assign names to rows using row. ...
  5. Character variables passed to data.
Jun 20, 2022

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? ›

List of Types of Functions
Based on ElementsOne One Function Many One Function Onto Function One One and Onto Function Into Function Constant Function
Based on EquationIdentity Function Linear Function Quadratic Function Cubic Function Polynomial Functions
2 more rows

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? ›

View requires a data frame like object, it does not accept a function (in base R).
...
In RStudio, there are (at least) 3 ways:
  1. Press the F2 key while cursor is on any function.
  2. Click on the function name while holding Ctrl or Command.
  3. 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
  1. Select a cell.
  2. Type the equal sign =. Note: Formulas in Excel always begin with the equal sign.
  3. Select a cell or type its address in the selected cell.
  4. Enter an operator. ...
  5. Select the next cell, or type its address in the selected cell.
  6. 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.

Videos

1. R demo: Using the 'as.numeric' and 'as.factor' functions with data frames
(Mike Crowson)
2. ggplot for plots and graphs. An introduction to data visualization using R programming
(R Programming 101)
3. How to write Recursive Functions
(Neso Academy)
4. #32 Python Tutorial for Beginners | Functions in Python
(Telusko)
5. Introduction to R Programming for Excel Users
(Data Science Dojo)
6. Visual Basic .Net Solve error expects the parameter which was not supplied in SQL server Database .
(Programming for Everybody)

References

Top Articles
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated: 08/27/2023

Views: 6766

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.