Running R functions stored in Google Drive

Hey folks! I’m trying to figure out how to use R functions that I’ve saved in Google Drive. I know we can import spreadsheets from Google Sheets into R, but what about actual R code?

Here’s what I want to do:

  1. Write an R function
  2. Save it in Google Drive and make it shareable
  3. Use it in R from anywhere, like with the source() command

I’m not looking to read data, just functions. It would be super handy for using my custom functions on different computers or servers.

Has anyone done this before? Any tips or tricks?

Here’s a simple function example to show what I mean:

quick_stats <- function(data, use_mean = TRUE, show_result = TRUE) {
  if (use_mean) {
    mid = mean(data)
    spread = sd(data)
    label = 'Mean'
  } else {
    mid = median(data)
    spread = mad(data)
    label = 'Median'
  }
  
  if (show_result) {
    print(paste(label, '=', mid))
    print(paste('Spread =', spread))
  }
  
  return(list(midpoint = mid, variation = spread))
}

Thanks for any help!

I found a workaround that might help. Instead of sourcing directly from Google Drive, you can use the googlesheets4 package to manage R functions stored as text in a Google Sheet cell. Once the function is saved as a string, you can retrieve it with read_sheet and execute it using eval(parse(text = …)).

For example, you can write:

library(googlesheets4)
sheet_url <- "your_sheet_url_here"
function_string <- read_sheet(sheet_url, range = "A1")
eval(parse(text = function_string))

This approach avoids the need to download files repeatedly and works efficiently across different devices. Just ensure proper authentication and exercise caution when executing code from external sources.

hey, i’ve done this before! u can use the httr package to fetch ur r script directly from google drive.
just grab the file id from ur share link, GET() the content, and eval(parse(text=content)).
no file saving needed. check ur drive sharing settings!

I’ve actually done something similar with my R functions stored in Google Drive. Here’s what worked for me:

Instead of using source() directly, I found it easier to use the googledrive package in R. First, you’ll need to set up authentication with your Google account. Then, you can use googledrive::drive_download() to fetch your R script from Drive.

Here’s a basic workflow:

  1. Install and load the googledrive package
  2. Authenticate with your Google account
  3. Use drive_download() to get your script
  4. source() the downloaded file

One caveat: this method downloads the file each time you run it, so it’s not ideal for functions you use frequently. For those, I’d recommend storing them in a package on GitHub instead.

Also, be mindful of security when sharing R scripts this way. Make sure you’re not exposing any sensitive information in your shared functions.