3.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.
3.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.
3.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.
3.6.3 All files names in a folder
The function list.files will find all files in a folder.
Note that full.names = TRUE if it is a full path. Otherwise, it is relative to the current working directory.
3.6.4 Merging all csv files in a folder
Using Reduce() and lapply() we can read all csv files from the folder, and merge them together.
First, we get all files names of csv files in a list by list.files().
Second, we use lapply() to read all csv files in a list:
readingcsv <- function(x){
read.csv(file = x,
header = TRUE,
stringsAsFactors = FALSE)
}
file.list <- lapply(file.names,readingcsv)
Finally, we use Reduce() to merge csv files one by one.