- Relational Operators in R
- Logical Operators in R
- Conditional Statements in R
- For Loop in R Programming
- While and Repeat Loop in R Programming
- Functions in R Programming
- Creating Functions in R
- Apply Functions in R
- Importing Data from External Data Sources in R
- Importing Data Using read.csv in R
- Import Data using read.table in R
- Importing Data Using data.table – fread in R
- Importing Data from Excel in R
- Using XLConnect in R Programming
- Importing Data from a Database in R
- SQL Queries from R
- Importing Data from Web in R
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
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 sd(stock_A)
sd() function takes the vector as an input and returns the standard deviation.
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
?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.