# R - Functions

June 21, 2017

I am writing this post who want to learn functions in R. I have solved few examples below. I have provided code also which will be helpful to understand few concepts in R.

Functions in any language basically used to achieve code re-usability. When one has to do repeat particular calculations or task multiple times ,then one can use functions. Function in R take any number of arguments  and return the output after processing it.

{

result = a+b

return(result)

}

Please check the following example for more details. I tried to select examples in such a way that all the important building block from R will be touched e.g. loops, conditional statements, sequences, vectors, data-frames, etc.

1. Create a function in R to compute the compound interest.

calCompoundInterest <- function(n,p,r)
{
A<-p*(1+r/100)^n
A[length(n)] - p
}
n<-1:5
p<-10000
r<-5
calCompoundInterest(n,p,r)

2. Calculate the factorial of a number by creating a function ‘calFactorial’.

calFactorial<-function(n)
{
total<-1
for(i in 1:n)
{
total<-total*i
}
total
}
calFactorial(5)

3. Write a function which takes vector as an input and calculate the Sharpe Ratio.
𝑆ℎ𝑎𝑟𝑝𝑒 𝑅𝑎𝑡𝑖𝑜= 𝑀𝑒𝑎𝑛 /𝑆𝑡𝑎𝑛𝑑𝑎𝑟𝑑 𝐷𝑒𝑣𝑖𝑎𝑡𝑖𝑜𝑛∗√252
(Use the vector: -171.47, 37.24, 265.20, -393.14, 54.65, -183.08, 116.95, 214.19, 356.28, 300.74, 144.74, -270.43, 243.06, 188.60, 373.49)

cal_details<-function(vec)
{
sharp.ratio<-(mean(vec)/sd(vec) )* sqrt(252)
sharp.ratio
}
cal_details(c(-171.47, 37.24, 265.20, -393.14, 54.65, -183.08, 116.95, 214.19, 356.28, 300.74, 144.74, -270.43, 243.06, 188.60, 373.49))

4. Create a function which calculates the sum for any value n and find f(4).

{
total <-0
for(i in 1:n)
total<- total + i
return(total)
}

5. Write a function which takes coefficients of quadratic equation as arguments and calculates the roots of the equation.

fun.findroots<-function(c_q_e)
{
a<-c_q_e
b<-c_q_e
c<-c_q_e

if(b*b < 4*a*c)
{
root1<-as.complex((-b + (sqrt(b*b-4*a*c)))/2*a)
root2<-as.complex((-b - (sqrt(b*b-4*a*c)))/2*a)
}else
{
root1<-(-b + (sqrt(b*b-4*a*c)))/2*a
root2<-(-b - (sqrt(b*b-4*a*c)))/2*a
}
vec<-c(root1,root2)
return(vec)
}
fun.findroots(sample(-40:20,3))

GitHub

Hope this helps to somebody who wants to learn basics in R!

Dattatray Shinde have over 6+ years of experience in Software Design, Development & Maintenance of Web Based Applications; worked on Healthcare, Insurance, E-commerce and Learning Management System domains. Over 2.5 + years as Data Scientist worked mainly in predictive analytics, survey analytics, risk analytics platforms.

##### Featured Posts

SAS - 1. Starting with SAS ... How to Install University edition?

March 20, 2017

1/5

June 21, 2017

January 19, 2014