# R Weekly Bulletin Vol - I

We are starting with R weekly bulletins which will contain some interesting ways and methods to write codes in R and solve bugging problems. We will also cover R functions and shortcut keys for beginners. We understand that there can be more than one way of writing a code in R, and the solutions listed in the bulletins may not be the sole reference point for you. Nevertheless, we believe that the solutions listed will be helpful to many of our readers. Hope you like our R weekly bulletins. Enjoy reading them!

### Shortcut Keys

1. To move cursor to R Source Editor - Ctrl+1
2. To move cursor to R Console - Ctrl+2
3. To clear the R console - Ctrl+L

### Problem Solving Ideas

#### Creating user input functionality

To create the user input functionality in R, we can make use of the readline function. This gives us the flexibility to set the input values for variables for our choice in the code is run.

Example: Suppose that we have coded a backtesting strategy. We want to have the flexibility to choose the backtest period. To do so, we can create a user input “n”, signifying the backtest period in years, and add the line shown below at the start of the code.

When the code is run, it will prompt the user to enter the value for “n”. Upon entering the value, the R code will get executed for the set period and produce the desired output.

n = readline(prompt = "Enter the backtest period in years: ")

#### Refresh a code in every x seconds

To refresh a code in every x seconds we can use the while loop and the Sys.sleep function. The “while loop” keeps executing the enclosed block of commands until the condition remains satisfied. We enclose the code in the while statement and keep the condition as TRUE. By keeping the condition as TRUE, it will keep looping. At the end of the code, we add the Sys.sleep function and specify the delay time in seconds. This way the code will get refreshed after every “x” seconds.

Example: In this example, we initialize the x value to zero. The code is refreshed every 1 second, and it will keep printing the value of x. One can hit the escape button on the keyboard to terminate the code.

x = 0
while (TRUE) {
x = x + 1 print(x)
Sys.sleep(1)
}

#### Running multiple R scripts sequentially

To run multiple R scripts, one can have the main script which will contain the names of the scripts to be run. Running the main script will lead to the execution of the other R scripts. Assume the name of the main script is “NSE Stocks.R”. In this script, we will mention the names of the scripts we wish to run within the source function. In this example, we wish to run the “Top gainers.R” and the “Top losers.R” script. These will be the part of the “NSE Stocks.R” as shown below and we run the main script to run these 2 scripts.

source("Top gainers.R")
source("Top losers.R")

Enclosing the R script name within the “source” function causes R to accept its input from the named file. Input is read and parsed from that file until the end of the file is reached, then the parsed expressions are evaluated sequentially in the chosen environment. Alternatively, one can also place the R script names in a vector, and use the sapply function.

Example:

filenames = c("Top gainers.R", "Top losers.R")
sapply(filenames, source)

#### Converting a date in the American format to Standard date format

The American date format is of the type mm/dd/yyyy, whereas the ISO 8601 standard format is yyyy-mm-dd. To convert a date from American format to the Standard date format we will use the as.Date function along with the format function. The example below illustrates the method.

Example:

# date in American format dt = "07/24/2016" # If we call the as.Date function on the date, it will
# throw up an error, as the default format assumed by the as.Date function is yyyy-mmm-dd.
as.Date(dt)

Error in charToDate(x): character string is not in a standard unambiguous format

# Correct way of formatting the date
as.Date(dt, format = "%m/%d/%Y")

[1] "2016-07-24"

#### How to remove all the existing files from a folder

To remove all the files from a particular folder, one can use the unlink function. Specify the path of the folder as the argument to the function. A forward slash with an asterisk is added at the end of the path. The syntax is given below.

Example:

unlink("C:/Users/Documents/NSE Stocks/*")

This will remove all the files present in the “NSE Stocks” folder.

### Functions Demystified

#### write.csv function

If you want to save a data frame or matrix in a csv file, R provides for the write.csv function. The syntax for the write.csv function is given as:

write.csv(x, file="filename", row.names=FALSE)

If we specify row.names=TRUE, the function prepends each row with a label taken from the row.names attribute of your data. If your data doesn’t have row names then the function just uses the row numbers. Column header line is written by default. If you do not want the column headers, set col.names=FALSE.

Example:

# Create a data frame
Ticker = c("PNB","CANBK","KTKBANK","IOB")
Percent_Change = c(2.30,-0.25,0.50,1.24)
df = data.frame(Ticker,Percent_Change)
write.csv(df, file="Banking Stocks.csv", row.names=FALSE)

This will write the data contained in the “df” dataframe to the “Banking Stocks.csv” file. The file gets saved in the R working directory.

#### fix function

The fix function shows the underlying code of a function provided as an argument to it.

Example:

fix(sd)

The underlying code for the standard deviation function is as shown below. This is displayed when we executed the fix function with “sd” as the argument.

function (x, na.rm = FALSE)
sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm))

The download.file function helps download a file from a website. This could be a webpage, a csv file, an R file, etc. The syntax for the function is given as:

where, url - the Uniform Resource Locator (URL) of the file to be downloaded destfile - the location to save the downloaded file, i.e. path with a file name

Example: In this example, the function will download the file from the path given in the “url” argument, and saved it in the D drive within the “Skills” folder with the name “betawacc.xls”.

url = "http://www.exinfm.com/excel%20files/betawacc.xls"
destfile = "D:/Skills/wacc.xls"
download.file(url, destfile)

### Next Step

We hope you liked this bulletin. In the next weekly bulletin, we will list more interesting ways and methods plus R functions for our readers.