## 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.

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

### 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.

suppressMessage(…)
suppressWarnings(…)

### 3.6.3 All files names in a folder

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

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

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().

setwd("C:/path")
file.names <-list.files(path = ".",
pattern="*.csv",
full.names = TRUE)

Second, we use lapply() to read all csv files in a list:

readingcsv <- function(x){
file.list <- lapply(file.names,readingcsv) 
merging <- function(x,y) {
df<-Reduce(merging,file.list)