functions

  • for common tasks and computations
  • helps to structure code
  • reduces code redundancies
  • integration into packages with documentation
myFunction <- function(arg1){
  print("I will now multiply you input with 5.")
  result <- arg1 * 5
  return(result)
}


a <- myFunction(arg1 = 8)
[1] "I will now multiply you input with 5."
a
[1] 40

If you need examples, all R package source codes consist of functions: https://github.com/r-spatial/sf/tree/master/R

Task
  • Write a function rmse that calculates the Root Mean Squared Error.
  • Test the function with the dataset below.

x = c(2,5,3,4)
y = c(2,6,5,5)
Task
  • Write a function calcNDVI that calculates the NDVI.
  • The function should have two raster bands as inputs and return one raster band.
  • Test the function with a satellite image.