How to make a Function in R

[This article was first published on The Practical R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This post is meant to show R users how to make their own functions. We’ll start with an easy example below.

Most of my posts provide R code that can be easily copied into R and replicated at home. This post will be a break from that process since functions require saving *.R files and calling them from other *.R files. Let’s begin.

First of all make a new R script file. This will become our function file. There is no difference between a script file and a function file in R. Both are *.R files.

We will make a simple function that multiplies a vector of data by 2. We start by defining our function using the

#make a function
my_function<- function(x){
  x*2
  
}

Now save this R file as “f_myfirstfunction.R” on your Desktop. Now let’s walk through the components of the function. We defined it as “my_function”. This is important as it is how we call the function. After that it’s the

Now we have to open a second R file. This will be the script file that we will use to call the function from. We’ll start this file by setting our working directory to the desktop with the functions getwd() and setwd. getwd() simply states your current working directory in R. setwd is used to change it to wherever you like.

#set the working directory
#rename "your User Name here" based on your user name
#example: owner, Emily, Bill
getwd()
setwd("C:/Users/your User Name here/Desktop")
currwd 

If you get the error, “Error in setwd(“C:/Users/your User Name here/Desktop”):
cannot change the working directory” that means you misspelled some part of your file path. Fix the error and run the code again.

Now we need to make a vector of data, so let’s use the function seq which makes a sequence of values. We’ll save our vector as “data”.

#make some data
data<- seq(from=1, to=10, by=1)
data

Next we have to import the function that we made into the R working space. This is very easy once we have set the working directory. Simply use the call source.

#import the function
source("f_myfirstfunction.R")

I should point out that you need quotations around the R file name. Also, if this file is not saved on the Desktop (the location we set the working directory to), this will give an error “Error in file (….. cannot open the connection”. If this happens move your function file “f_myfirstfunction.R” to your working directory.

Now we will use our awesome new function that we made to multiply the vector “data” by 2. Of course we could just code data*2, but that’s not the point. We’re learning how to write a function.

#call the function
my_function(data)

Awesome! You ran your first function! The R console will spit out the answer:
[1] 2 4 6 8 10 12 14 16 18 20
If we wanted to do something more useful with this output we should save it as a variable. Let’s use data2.

#call the function
data2 <- my_function(data)

This time we get no output from R, but if we type in the variable data2 we get our familiar output:
[1] 2 4 6 8 10 12 14 16 18 20

One important thing to remember when using functions in R is that it doesn’t matter what you save you function file as. When you call your function, you’re using the defined name within the function file code.

#rename the function call to 'times2'
times2<- function(x){
  x*2
}

#rename the function again
zzzzz<- function(x){
  x*2
}

This is the same function saved in file “f_myfirstfunction.R”, but the function name has been changed. Again the function name is what is called from R.

I’ve listed the full text of the script file “call function.R” and the function file “f_myfirstfunction.R” below.

Hope this helps! Happy function writing!

#"call function.R"
#set the working directory
getwd()
setwd("D:/D Documents/wordpress/practicalR/make a function")
currwd

#make some data
data<- seq(from=1, to=10, by=1)
data

#import the function
source("f_myfirstfunction.R")

#call the function
my_function(data)

#call the function - save output as variable
data2 <- my_function(data)
 

#"f_myfirstfunction.R"
my_function<- function(x){
  x*2
}

To leave a comment for the author, please follow the link and comment on their blog: The Practical R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)