Last active
June 16, 2016 18:19
-
-
Save omri374/73f9ef8165ce7843e85458c10d2d41cf to your computer and use it in GitHub Desktop.
R dropbox persistency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(rdrop2) | |
## This script uses both local storage and dropbox to store files. When saving, the file is saved in both locations. | |
## When loading, the file is first looked for locally, and if not found, is looked for on dropbox. | |
## Could be used in services such as shinyapps in which you don't have access to persistent storage on the machine. | |
## Note that you have to authenticate your dropbox API before using rdrop2's methods. | |
## Global param to set dropbox interface on/off | |
USE_DROPBOX <<- T | |
## Writes a data frame to dropbox. | |
## similar to write.csv(...) | |
saveDfToDropbox <- function(df,folder = "data",filename,...){ | |
filepath <- paste0(folder,"/",filename) | |
write.csv(x = df, file = filepath,row.names=FALSE,na="",...) | |
if(USE_DROPBOX){ | |
saveFileToDropbox(filepath,folder = folder) | |
} | |
} | |
## Copies a file from the local machine to dropbox | |
saveFileToDropbox <- function(filepath,folder = "data") { | |
# Upload the file to Dropbox | |
drop_upload(filepath, dest = folder) | |
} | |
## same as read.csv(...) | |
loadFromDropbox <- function(filepath,localpath = getwd(),...) { | |
if(file.exists(filepath)){ | |
data <- read.csv(file = filepath,...) | |
} else{ | |
if(USE_DROPBOX && fileExistsOnDropbox(filepath)){ | |
data <- drop_read_csv(file = filepath,dest = localpath,...) | |
} else{ | |
data <- NULL | |
} | |
} | |
if(is.null(data)){ | |
return(data.frame()) | |
} | |
data | |
} | |
## Checks if a file exists at a specific path | |
## same as file.exists(...) | |
fileExistsOnDropbox <- function(filepath){ | |
if(USE_DROPBOX){ | |
drop_exists(filepath) | |
} else{ | |
file.exists(filepath) | |
} | |
} | |
## Lists all the files in a specific path | |
## same as list.files() | |
listFilesDropbox <- function(path){ | |
if(USE_DROPBOX){ | |
files <- drop_dir(path) | |
files.list <- gsub(path,"",files$path) | |
files.list <- gsub("/","",files.list) | |
} else{ | |
files.list <- list.files(paste0(getwd(),"/",path)) | |
} | |
files.list | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment