5-Minute Guide to Calling Functions from R Scripts
By: Emily A. Halford
Tags: Code, R Tutorial, R, Google Trends, Editors Pick

5-Minute Guide to Calling Functions from R Scripts

R code tutorial using Google Trends data.

Photo by Christina Morillo from Pexels

You’ve likely heard the popular guideline that if you find yourself copying and pasting code more than 3 times, you should write it as a function. While you can write and store these functions at the top of your R Markdown files, this approach can get messy and is counterproductive if you end up copying and pasting the functions into multiple files. Often, the best way to stay organized is to write your functions in a script and to call them from any additional files where they’re needed.

To demonstrate this process, I will use 3 functions to conduct a very simple change point analysis of Google searches containing the words “supreme court” over the past month.

First, create your functions

In an R script, we write three simple functions. The first plots the Google Trends data, the second performs a simple change point analysis using the bcp() function from the “bcp” package, and the third plots the results of this analysis.

google_graph = function(data, date, observation, graph_title) {



data %>%

ggplot() +

geom_line(aes(x = date, y = observation),

color = "#09557f",

alpha = 0.6,

size = 0.6) +

labs(x = "Date (Start of Week)",

y = "Relative Proportion",

title = graph_title) +

theme_minimal() +

scale_x_date(date_breaks = "1 week") +

theme(axis.text.x = element_text(angle = 45))



} bcp_analysis = function(observation, data) {



set.seed(100)



bcp = bcp(observation)



prob = bcp$posterior.prob

prob = as.data.frame(prob)



bcp_dataframe = cbind(data, prob) %>%

select(date, prob)



} bcp_plot = function(dataframe){



dataframe %>%

ggplot() +

geom_line(aes(x = date, y = prob),

color = "#09557f",

alpha = 0.6,

size = 0.6) +

labs(x = "",

y = "Posterior Probability",

title = "Changepoint Probabilities") +

theme_minimal() +

ylim(0, 1) +

scale_x_date(date_breaks = "1 week") +

theme(axis.text.x = element_text(angle = 45))



}

I’ve also checked this “Source on Save” box. If you check this box, then the file will be sourced automatically to the global environment when you save changes to your functions in the script.

Connect to your functions

Connecting to functions stored in a script from an R Markdown file is very similar to connecting to functions stored in a package. Instead of using a library() statement, we use a source() statement and indicate the script’s path name. In this case, we use the following code:

source("./functions.R")

When we run this line of code, the functions contained within the script automatically appear in the Global Environment. The connection was successful!

Use your functions

First, we’ll just use the gtrends() function from the “gtrendsR” package to pull Google search volume for searches containing the words “supreme court” in the United States over the past month. A mutate step is also used to convert the “date” variable to a date format:

data = gtrends(keyword = "supreme court", geo = "US",

time = "today 1-m")$interest_over_time %>%

mutate(date = as.Date(date))

Now we have data to use in our functions! We use the google_graph() function the same way we would use any other function, allowing us to easily plot the data:

google_graph(data, data$date, data$hits, ‘Google Searches for “Supreme Court”’)

The plot looks good! Unsurprisingly, there is a massive surge in searches containing “supreme court” following the death of Supreme Court Justice Ruth Bader Ginsburg. Let’s use the bcp_analysis() and bcp_plot() functions to see if this spike represents a significant change point in this time-series object. Again, we use the functions the same way we would if we were using functions from a loaded package:

bcp_dataframe = bcp_analysis(data$hits, data) bcp_plot(bcp_dataframe)

Several days following the death of Ruth Bader Ginsburg have posterior probabilities of 1.00, indicating that searches containing the words “supreme court” likely changed in a statistically meaningful way around this time.

It’s as simple as that! If we wanted to plot and analyze several different sources of data in separate Rmd files, it would be as easy as connecting those files to our “functions” script with a source() statement and using our functions.