We can write our own functions in R. This will be useful as it will prevent us having to re-write difficult code over and over again. Remember the return calculation that we did last week. I do not want to have to do that again.
A function is an object just like everything else and we use the
function function to create a new function. For
example,
mysquare <- function(x){
mynumber <- x^2
return(mynumber)
}
Look at this carefully. Make sure that you know what is happening.
Write a function that will double the number that you input
Write a function that will multiply any number by 5
Update the function so that it will multiply one number by another
Remember that the equation for future values is
\[FV = PV * (1 + R)^n\]
where FV is the future value, R is the rate of return and n is the number of years into the future. Therefore, if I have $100 and there is an interest rate or rate of return of 5% (0.05), I will have:
\[100 * (1 + 0.05)^5\]
in 5 years.
Now we write a function to make this calculation.
futurevalue <- function(PV = 100, R = 0.05, n = 1){
FV = PV * (1 + R)^n
return(FV)
}
futurevalue()
## [1] 105
futurevalue(PV = 25.5, R = 0.055, n = 4)
## [1] 31.59003
}
Re-arrange the future value into present value:
\[PV = \frac{FV}{(1 + R)^n}\]
Write the function for Present value.
You have 3 bonds that will mature at 100 in 5, 3 and 2 years. If the rate of return for all the bonds is 3.5%, what should be the price of these bonds?
This is an advanced function that will calculate the key descriptive statistics for our series.
mystats <- function(x){
if(NA %in% x){
x <- x[!is.na(x)]
warning("NA removed")
}
mynumber <- length(x)
mymean <- mean(x)
mymed <- median(x)
mysd <- sd(x)
myskew <- sum((x-mymean)^3/mysd^3)/mynumber
mykurt <- sum((x - mymean)^4/mysd^4)/mynumber - 3
mymax <- max(x)
mymin <- min(x)
return(c("Number" = round(mynumber, 0),
"Mean" = round(mymean, 4),
"Median" = round(mymed, 4),
"St Dev" = round(mysd, 4),
"Skew" = round(myskew, 2),
"Kurtosis" = round(mykurt, 2),
"Min" = round(mymin, 4),
"Max" = round(mymax, 4)))
}
mydata <- rnorm(10000)
mystats(mydata)
## Number Mean Median St Dev Skew Kurtosis Min
## 10000.0000 0.0043 0.0012 1.0002 -0.0300 -0.0200 -3.5981
## Max
## 4.1257
Re-run the code for Bank of America and the S&P 500 that we had last week and then calculate the descriptive statistics
Turn the re-basing calculation that we did last week into a function
Turn the return calculation into a function
Put all the functions into a file that you can access. Load these functions using ``source(‘functionfilename’)```