Loading R functions from Google Documents

I know you can work with Google Sheets data in R by importing published spreadsheets. But what if I want to do something different? I have some R functions that I wrote and stored in a Google Doc. I want to be able to load these functions directly into R using something like the source() command.

Here’s what I’m trying to accomplish:

  1. Write my R functions and save them in a Google Document
  2. Make the document publicly accessible so no authentication is needed
  3. Use a command in R to load these functions from the Google Doc

This would be really helpful when I’m working on different computers and need quick access to my custom functions without having to copy files around.

Here’s an example of the type of function I want to store:

calc_stats <- function(data_vec, use_median=FALSE, show_output=FALSE) {
  if (use_median) {
    middle_val <- median(data_vec)
    spread_val <- mad(data_vec)
  } else {
    middle_val <- mean(data_vec)
    spread_val <- sd(data_vec)
  }
  
  if (show_output) {
    if (use_median) {
      print(paste("Median:", middle_val, "MAD:", spread_val))
    } else {
      print(paste("Mean:", middle_val, "SD:", spread_val))
    }
  }
  
  return(list(center=middle_val, spread=spread_val))
}

Is there a way to make this work? Any suggestions would be appreciated.

This approach works great, but watch out for a few things. When you publish the Google Doc, choose “Plain text” instead of HTML - otherwise R tries to parse HTML tags and throws errors. Google sometimes adds weird characters or formatting that breaks your functions, so test everything after uploading. I keep a backup copy of my functions in a regular .R file just in case Google’s formatting screws something up. The convenience is worth it though - I use this for sharing utility functions across projects and it saves tons of time once you get the hang of it.

yep! so just publish the google doc as plain text, get the shared link, and use source() in R to load it. it’s a neat trick for keeping your functions updated on all your devices.

I’ve been doing this for two years and there’s one step that always trips people up. After you publish your Google Doc as plain text, you have to modify the sharing URL. Replace ‘/edit’ at the end with ‘/export?format=txt’ - otherwise R gets HTML wrapper code instead of pure R syntax and source() fails. Here’s the workflow: write functions in Google Doc, publish to web as plain text, grab the share link, swap the URL ending, then use source(“your-modified-url”) in R. Bonus: any changes you make to the doc automatically sync to all your R sessions, so it’s great for version control.