After completing this tutorial, you will be able to:
- Calculate NDVI using NAIP multispectral imagery in
- Describe what a vegetation index is and how it is used with spectral remote sensing data.
What You Need
You will need a computer with internet access and
R Studio loaded to complete this lesson.
Where to Store Your Functions
When you create a function to use in your analysis, you often create it and store it at the top of your script or
.Rmd file as a first step. However, lots of functions at the top of your code can make your code dense and harder to read.
It is good practice to create separate
R scripts that you can use to store sets of related functions. You can then call those functions using the
source() function, at the top of your script in the same way that you call an
R will then load those functions into memory and you can use them!
Sourcing functions is good practice because it is:
- Reusable: It allows you to reuse functions over and over using the same code (i.e. you don’t have to copy and paste the function into each new analysis script).
- Easy to Maintain: It allows you to quick fix a function that doesn’t work properly - only once.
- Sharable: In the same way that a library can be used by anyone, you can share your
Rscript containing your functions with anyone too. This is the first step towards creating an
How to Source Functions in R
To source a set of functions in
- Create a new
R Script(.R file) in the same working directory as your
Rscript. Give the file a descriptive name that captures the types of functions in the file.
- Open that
R Scriptfile and add one or more functions to the file.
- Save your file.
- Open your
- At the top of your file, add the
.R script is in your main working directory then it won’t have a path element before it like
If it’s in a different directory, adjust the path accordingly. Once you run the code containing the
source() function, all of the functions in your
.R file will load into your global environment. You can now use them in your script!