5.6 Tricks

There are some minor tricks to help you in coding. For long codes, we sometimes want to calculate the time required to complete a task, and we might improve the efficiency of the code if it is too slow.

5.6.1 Timing code

To get the current time, we may use Sys.time(). Put this at the beginning and the end of the code. Then the difference is the run time.

t1 <- sys.time()
#…run code here …#
t2 <- sys.time()

5.6.2 Suppress annoying message

R tends to give a lot of warning and messages when you run a long code. Sometimes you want to suppress them to keep your console window clean.


5.6.3 All files names in a folder

The function list.files will find all files in a folder.

# full.names = TRUE for full path
filenames <- list.files(path = "./folder/", full.names = TRUE)

Using Reduce() and lapply() we can read all csv files from the folder, and merge them together

file.names <-list.files(path = ".", 
                        full.names = TRUE)
file.list <- lapply(file.names, 
                      read.csv(file = x,
                               header = TRUE,
                               stringsAsFactors = FALSE)})
df<-Reduce(function(x,y) {merge(x, y, all=TRUE)},