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.

Image for post

Image for post

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!

Image for post

#code #r #r-tutorial #editors-pick #google-trends

5-Minute Guide to Calling Functions from R Scripts
1.45 GEEK