Formal Arguments in R

Introduction to Formal Arguments in R

Formal arguments in R are essentially variables you define within a function’s code block. These arguments act as placeholders for the data that are provided when a user uses the function. Formal are the formal arguments of function returned as an object of class pairlist which can be thought of as something similar to a list with an important difference:

is.null(pairlist())
is.null(list())

That is a pairlist of length zero is NULL while a list is not.

Specifygin Formal Arguments Positions

Formal arguments in R can be specified by position or by name and we can mix positional matching with matching by name. The following are equivalent.

mean(x = 1:5, trim = 0.1)
mean(1:5, trim = 0.1)
mean(x = 1:5, 0.1)
mean(1:5, 0.1)
mean(trim = 0.1, x = 1:5)
formal arguments in R Language

Functions Formals Default Values

Functions formals may also have the construct symbol=default, which unless differently specified, forces any argument to be used with its default value. Specifically, functions mean() also have a third argument na.rm that defaults to FALSE and as a result, passing vectors with NA values to mean() returns NA.

mean(c(1, 2, NA))

while by specifying na.rm=TRUE we get the mean of all non-missing elements of vector x.

mean(c(1, 2, NA), na.rm = TRUE)

we can redefine mean() function that defaults na.rm to TRUE by simply

mean(c(1, 2, NA))

Now we have a copy of mean.default() in our globalenv:

exists("mean.default", envir = globaenv())

also, notice

environment(mean.default)

The … Argument in a Function

The … argument of a function is special and can contain any number of symbol=value arguments. The … argument is transformed by R into a list that is simply added to the formal list:

h<-function(x, …){
            0
}

formals(h)

The … argument can be used if the number of arguments is unknown. Suppose one wants to define a function that counts the number of rows of any given number of data frames. One can write:

count_rows<-function(…){
     list<-list(…)
     lapply(list, nrow)
}

count_rows(airquality, cars)

By effectively using formal arguments in R Language, one can create reusable and adaptable functions that make the R code more concise and efficient.

https://itfeature.com

https://gmstat.com

Leave a Reply

Discover more from R Language Frequently Asked Questions

Subscribe now to keep reading and get access to the full archive.

Continue reading