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.
Example: Addition of two numbers
add = function(a,b)
result = a+b
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[length(n)] - p
2. Calculate the factorial of a number by creating a function ‘calFactorial’.
for(i in 1:n)
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)
sharp.ratio<-(mean(vec)/sd(vec) )* sqrt(252)
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).
for(i in 1:n)
total<- total + i
5. Write a function which takes coefficients of quadratic equation as arguments and calculates the roots of the equation.
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)
root1<-(-b + (sqrt(b*b-4*a*c)))/2*a
root2<-(-b - (sqrt(b*b-4*a*c)))/2*a
Code Download link -
Hope this helps to somebody who wants to learn basics in R!