It is possible to write your own functions with the
function() function. The structure for a function would
be:
your_name_for_function <- function(argument 1, argument 2...argument n) {
< the function details >
}
For example, to create a function that will double any number that is put into it,
mydouble <- function(x) {
x^2
}
mydouble(2)
## [1] 4
mydouble(4.5)
## [1] 20.25
combiner which will add two
numbers together.In order to create a function that will rebalance any series there are a number of necessary steps:
Let’s call this myrebase.
myrebase <- function(data = x, base = 1, value = 100){
mydata <- x/x[base] * value
return(mydata)
}
Notice that I have added return() to the end of the
function. This is not necessary as the function will return (or
preserve) the last object that was created (mydata in this
case). However, it is good practice because it will make you think what
you want to be returned. Everything else will disappear after the
function run has been completed.
Now we need to test the function to make sure it works. Make some toy data and run it in different ways.
x <- 1:3
myrebase(x)
## [1] 100 200 300
myrebase(x, base = 3)
## [1] 33.33333 66.66667 100.00000
myrebase(x, base = 3, value = 3)
## [1] 1 2 3
myrebase(x, base = 3, value = 1)
## [1] 0.3333333 0.6666667 1.0000000
This is a function that will calculate the percentage change or return.
mypercent <- function(x, reverse = FALSE, lag = 1){
if(reverse == TRUE){
myreturn <- x[1:(length(x) - lag)] /
x[(lag + 1):length(x)] - 1
myvector <- c(myreturn, rep(NA, lag))
} else {
myreturn <- x[(lag + 1):length(x)] /
x[1:(length(x) - lag)] - 1
myvector <- c(rep(NA, lag), myreturn)
}
return(myvector)
}
There is a lot here but it is a very versatile function.
if() function. If we tell the
function that the data is in reverse it will adjust the
calculation.x <- 1:3
mypercent(x)
## [1] NA 1.0 0.5
mypercent(x, reverse = TRUE)
## [1] -0.5000000 -0.3333333 NA
mypercent(x, lag = 2)
## [1] NA NA 2
mypercent(x, reverse = TRUE, lag = 2)
## [1] -0.6666667 NA NA
Once you have functions you can put them in a single folder and call it at the start of any work by using the
source('./R/functions.R')
Note, './R/functions.R' must reflect the place where the
functions are compared to where you are now.