Writing Your Own Functions In R

write your own functions in R

There is so much in common we do whenever we start writing an R script. Recently we have identified a few things which are pretty repetitive and it only helps if one function does it all. Lets see how we can run our own functions in R.

The objective of publishing this article is to help those,

  1. Who write repeated lines of codes in every R script
  2. Who are willing to write their own Custom R functions

There are so many times we receive data and we need to process that and store somewhere. Ideally, we should have our files organized as that helps us later in finding these files quicker and easier. I thought to myself, how would it be, if I could write a function which will automate the following tasks for me,

  1. Set Working Directory
  2. Turn off Scientific notations
  3. Set Version for files to be saved with a timestamp.
  4. Create Required folders, Input, Output, and Backup. It also creates a Time Stamp folder inside the Input folder.
  5. Moves all files to the Input directory for further processing.

All I need to do is create one folder and dump all files there and run the function in an R script stored in that folder.

do_all_req_stuff<-function(){

libraries<<-c("tidyverse","filesstrings","tools")

a<-suppressWarnings(sapply(libraries,require,character.only=T))

unlib<-c()

if(FALSE %in% suppressWarnings(sapply(libraries,require,character.only=T))){

unlib<-c(unlib,names(a[grep(FALSE,a)]))

install.packages(unlib,dependencies = T)

print(sapply(libraries,require,character.only=T))

}else{

print(sapply(libraries,require,character.only=T))

}

######Setting Work Directory===Disabling Scientific Notations===Creating Required Directories===Define Version#####

cdir<<-(dirname(rstudioapi::getSourceEditorContext()$path))

setwd(cdir)

options(scipen = 999)

v<<-paste0(format(Sys.Date(),"%b_%d_%Y"))

##########################################Required Directories##############################################

input_directory<<-paste0(cdir,"/","Input")

output_directory<<-paste0(cdir,"/","Output")

backup_directory<<-paste0(cdir,"/","Backup")

input_timestamp<<-paste0(input_directory,"/",v)

list_of_directories<-c(input_directory,output_directory,backup_directory,input_timestamp)

#####Create Required Directories######

for(i in list_of_directories){

if(dir.exists(i)==F)

{

dir.create(i)

print(paste(i,"created..."))

}

else

{

print(paste("Directory:",i, "already Exists..."))

next

}

}
</pre>
#############Copy Files from cdir to input###############


files&lt;&lt;-grep(list.files(cdir,recursive = F), pattern='.R', inv=T, value=T) ####You can use the pattern as per need###

dirs&lt;-list.dirs(cdir,full.names = F) %&gt;% .[2:length(.)]

files&lt;&lt;-setdiff(files,dirs)

C=0

if(length(files)==0){

print("No files to move to Input Directory!")

}else{

for(i in files){

C=C+1

file.move(paste0(cdir,"/",files[C]),input_timestamp)

print(paste(files[C],"moved to Destination Folder..."))

}

if(C==length(files)){

print("All Files Moved...")

# print(paste("Setting value of C to Default"))

C=0

# print(paste("C =",C))

}

}

}

do_all_req_stuff()

We can always modify this function to meet our specific needs, for example, someone might want to load all required libraries along with this function can add an optional argument to the function and within the function, they can specify the following line of code.

By default, it does load a specific set of libraries we need to create this function. As an alternative and probably an easier option one can simply add the required set of libraries in the “libraries” vector inside the function.


#######This helps in loading all required libraries in one go#######

#### Make sure the argument supplied is a vector of all required libraries ####

&amp;nbsp;

argument_to_be_supplied&lt;-c("tidyverse","zoo",...) &lt;-Specify this outside the function

&amp;nbsp;

sapply(argument_to_be_supplied, require, character.only=T) &lt;-Add this step inside the function

I hope this article helps some of you at least in automating these minor tasks with the help of one single function and also maintaining a proper folder structure for good data management.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.