Functions in functions
To write clean code, sometimes it is useful to use functions inside of other functions. This let's you use the result of one function directly in another one, without having to create an intermediate variable. You have actually already seen an example of this with print()
and paste()
.
company <- c("Goldman Sachs", "J.P. Morgan", "Fidelity Investments")
for(i in 1:3) {
print(paste("A large financial institution is", company[i]))
}
[1] "A large financial institution is Goldman Sachs"
[1] "A large financial institution is J.P. Morgan"
[1] "A large financial institution is Fidelity Investments"
paste()
strings together the character vectors, and print()
prints it to the console.
The exercise below explores simplifying the calculation of the correlation matrix using nested functions. Three vectors of stock prices, apple
, ibm
, and micr
, are available for you to use.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- First,
cbind()
them together in the order ofapple
,ibm
,micr
. Save this asstocks
. - Then, use
cor()
onstocks
. - Now, let's see how this would work all at once. Use
cbind()
inside ofcor()
with the 3 stock vectors in the same order as above to create the correlation matrix.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# cbind() the stocks
stocks <- ___
# cor() to create the correlation matrix
___
# All at once! Nest cbind() inside of cor()
___