Reader small image

You're reading from  Learning Quantitative Finance with R

Product typeBook
Published inMar 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781786462411
Edition1st Edition
Languages
Right arrow
Authors (2):
Dr. Param Jeet
Dr. Param Jeet
author image
Dr. Param Jeet

Dr. Param Jeet is a Ph.D. in mathematics from one of India's leading technological institute in Madras (IITM), India. Dr. Param Jeet has a couple of mathematical research papers published in various international journals. Dr. Param Jeet has been into the analytics industry for the last few years and has worked with various leading multinational companies as well as consulted few of companies as a data scientist.
Read more about Dr. Param Jeet

PRASHANT VATS
PRASHANT VATS
author image
PRASHANT VATS

Prashant Vats is a masters in mathematics from one of India's leading technological institute, IIT Mumbai. Prashant has been into analytics industry for more than 10 years and has worked with various leading multinational companies as well as consulted few of companies as data scientist across several domain.
Read more about PRASHANT VATS

View More author details
Right arrow

Functions


In this section, we will provide some examples of built-in functions that already exist in R and also construct a user-defined function for a specific task.

A function is a collection of statements put together to do a specific task.

R has a lot of built-in functions and users can define their own functions.

According to their requirement, in R, the interpreter passes control to the function object along with the arguments required for the accomplishment of the task designated for the function. After completing the task, the function returns the control to the interpreter.

The syntax for defining a function is as follows:

>function_name<-function(arg1, arg2,...){ 
>+function body 
>+} 

Here:

  • Function name: This is the name of the defined function and is stored as an object with this name.

  • Arguments: Arguments are the required information needed for the function to accomplish its task. Arguments are optional.

  • Function body: This is a collection of statements that does the designated task for the function.

  • Return value: The return value is the last expression of a function which is returned as an output value of the task performed by the function.

Please find here an example of some of the inbuilt functions along with their results when executed:

>print(mean(25:82)) 
[1] 53.5 
>print(sum(41:68)) 
[1] 1526 

Now we will look at how to build the user-defined functions. Here we are trying to find the square of a given sequence.

The name of the function is findingSqrFunc and takes the argument value, which must be an integer:

>findingSqrFunc<-function(value){ 
>+for(j in 1:value){ 
>+sqr<-j^2 
>+print(sqr) 
>+} 
>+} 

Once the preceding code gets executed, we call the function:

>findingSqrFunc(4) 

We get the following output:

[1] 1 
[1] 4 
[1] 9 
[1] 16 

Calling a function without an argument

Construct a function without an argument:

>Function_test<-function(){ 
>+ for(i in 1:3){ 
>+ print(i*5) 
>+ } 
>+ } 
>Function_test() 

On executing the preceding function without arguments, the following output gets printed:

[1] 5 
[1] 10 
[1] 15 

Calling a function with an argument

The arguments to a function can be supplied in the same sequence as the way it has been defined. Otherwise the arguments have to be given in any order but assigned to their name. Given here are the steps for creating and calling the functions:

  1. First create a function:

            >Function_test<-function(a,b,c){ 
            >+ result<-a*b+c 
            >+ print(result) 
            >+ } 
    
  2. Call the function by providing the arguments in the same sequence. It gives the following output:

            >Function_test(2,3,4) 
            [1] 10 
    
  3. Call the function by names of arguments in any sequence:

            >Function_test(c=4,b=3,a=4) 
    

This gives the following output:

[1] 16 

How to execute R programs

In this section, we will discuss different ways of executing R programs.

How to run a saved file through R Window

For running a program in the R workspace, follow these steps:

  1. Open R (double-click on the desktop icon or open the program from Start).

  2. Click on File and open the script.

  3. Select the program you want to run; it will appear in an R Editor window.

  4. Right-click and Select All (or type Ctrl + A).

  5. Right-click and Run Line or Selection (or type Ctrl + R).

  6. The output will appear in the R console window.

How to source R script

Please perform the following steps for sourcing the R code:

  1. First check your working directory. It can be checked by the following code:

            >print(getwd()) 
    
  2. On running the preceding code, if it gives the path of the designated folder, it is fine. Otherwise, change the working directory by using the following code:

            >setwd("D:/Rcode")  
    
  3. Change the destination directory according to your need and then run the required code using the following code:

            >Source('firstprogram.r') 
    

For example, let's say the program firstprogram.r has the following code in it:

  a<-5 
print(a) 

Upon sourcing, it will generate the output 5 at the console.

When you want to tell R to execute a number of lines of code without waiting for instructions, you can use the source function to run the saved script. This is known as sourcing a script.

It's better to write the entire code in Studio Editor and then save it and source the entire script. If you want to print an output in source script then please use the print function to get the desired output. However, in the interactive editor, you do not need to write print. It will give it by default.

In other operating systems, the command for running the program remains the same.

Comments are parts of a program that are ignored by the interpreter while executing the actual program.

Comments are written using #; for example:

#this is comment in my program. 
Previous PageNext Page
You have been reading a chapter from
Learning Quantitative Finance with R
Published in: Mar 2017Publisher: PacktISBN-13: 9781786462411
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Dr. Param Jeet

Dr. Param Jeet is a Ph.D. in mathematics from one of India's leading technological institute in Madras (IITM), India. Dr. Param Jeet has a couple of mathematical research papers published in various international journals. Dr. Param Jeet has been into the analytics industry for the last few years and has worked with various leading multinational companies as well as consulted few of companies as a data scientist.
Read more about Dr. Param Jeet

author image
PRASHANT VATS

Prashant Vats is a masters in mathematics from one of India's leading technological institute, IIT Mumbai. Prashant has been into analytics industry for more than 10 years and has worked with various leading multinational companies as well as consulted few of companies as data scientist across several domain.
Read more about PRASHANT VATS