Functions in R Programming

Functions are an important concept in R and we will be using it all the time. In fact, we have already been using functions in our previous examples. For example, we used the summary() to summarize an R object. Similarly, we used the str() function to learn about the structure of an R object.

R functions are objects that evaluate multiple expressions using arguments that are passed to them.

To understand how to use functions, let's take the function to calculate standard deviation in R. The function is defined as sd().

Let's take our vector of stock prices for the past five days. We can use the sd() function to calculate its standard deviation.

#Stock A's Price Data
stock_A <- c(10, 8, 9, 11, 12)
#Calculate Standard Deviation of Stock A

The sd() function takes the vector as an input and returns the standard deviation.

[1] 1.581139

Function Help

Functions have named arguments which potentially have default values. To learn about how to use a function or its argument list, we can use R documentation. For example, to get help on the sd() function type help(sd) or ?sd. This will open the R documentation with details of the function as shown below:

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.