R Programming - Part 2 - Functions

05 Oct 2020 - Benjamin Loi

Introduction

This article will describe the principles and usage of functions in R.

Input and Output of Functions

Functions always take some inputs and return outputs. We have already encountered some functions like print() displaying the output on the screen. Inputs, also known as arguments, are supplied inside the parenthesis after the function name. Outputs can be printed, or assigned to some variables. It is possible to have multiple inputs and outputs. In case of multiple input, they are separated by a comma. We show an example of the function sum() which computes the sum of entries of all arguments provided.

R-02-00

Information about a function can be seen when the function name is being typed. An auto-completion box will appear, hovering the mouse on the function name allows the user to take a look at a short explanation of the function. Full documentation can be found by applying help().

R-02-01
R-02-02

Commonly Used Functions

Some commonly used functions are summarized in the table below.

Functions Usage
sum() Explained in the paragraph Above.
mean() Evaluates the mean of all elements in a vector. Example: mean(c(1,2,3)) gives 2.
median(), var() Calculate the median and variance of all elements in a vector. Similar to mean() above.
min(), max() Find the minimum and maximum of all entries supplied. Example: min(c(1,2,3)) gives 1.

Named Arguments

To improve clarity, when we are calling a function, the names of the arguments can be explicitly written out if they are defined in the function. It is in the form of [argument name] = [argument value]. Named arguments are often found as optional arguments. When such arguments are provided, they override the default values. An example of paste() is shown below which combines strings with a separator specified in the named argument sep=.

R-02-03

Sequences and Matrice

We can create a sequence, apart from :, by using the function seq(), where the lower limit and upper limit are supplied first, and then the step size can be specified by the named arguments by=. Notice that the end point is always included.

R-02-04

The vector sequence can be reshaped into a matrix through the function matrix(). The output shape has to be specified in the named arguments nrow= and ncol=. By default the elements are arranged along columns.

R-02-05

Inner product of vectors and matrices can be carried out by the operator %*%, as demonstrated in the example below.

R-02-06

Previous: Part 1 - Basic Operations Next: Part 3 - If-then-else Statement

Last Update: 2020-10-12