Last updated: 2024-12-31

Checks: 7 0

Knit directory: R_tutorial/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20241223) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 2ba13d6. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Functions.Rmd) and HTML (docs/Functions.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 2ba13d6 Ohm-Np 2024-12-31 wflow_publish("analysis/Functions.Rmd")
html 38b9de1 Ohm-Np 2024-12-31 Build site.
Rmd 1c127b5 Ohm-Np 2024-12-31 wflow_publish("analysis/Functions.Rmd")
html c335a5f Ohm-Np 2024-12-30 Build site.
Rmd 96baf68 Ohm-Np 2024-12-30 wflow_publish("analysis/Functions.Rmd")

Functions are blocks of code that perform a specific task in R. They allow us to encapsulate logic and reuse it across different parts of the code, making our scripts more modular, efficient, and easy to debug. Functions are one of the most powerful tools in R and are commonly used in data analysis, machine learning, and statistical programming.

By using functions, we can:

  • Avoid repetitive code
  • Break complex tasks into smaller, manageable pieces
  • Improve readability and maintainability of your code

Creating Functions in R

In R, a function is created using the function() keyword. The basic syntax for defining a function is:

my_function <- function(arg1, arg2) {
  # function body
  result <- arg1 + arg2
  return(result)
}

Here’s what each part means:

  • my_function: The name of the function.
  • function(arg1, arg2): The definition of the function with its arguments.
  • {}: The body of the function where the logic is written.
  • return(result): The value that is returned by the function.

Example:

# A simple function to add two numbers
add_numbers <- function(a, b) {
  sum <- a + b
  return(sum)
}

# Call the function
add_numbers(5, 3)
[1] 8

Function with Multiple Arguments

Functions can have multiple arguments, and you can pass values in the form of position or by explicitly naming the arguments when calling the function.

# A function to calculate the area of a rectangle
rectangle_area <- function(length, width = 2) {  # Default value for width
  area <- length * width
  return(area)
}

# Call the function with default width
rectangle_area(5)
[1] 10
# Call the function with a specific width
rectangle_area(5, 3)
[1] 15

In the above example, the argument width has a default value of 2. If you don’t provide a value, R will use this default.

Downloading Geospatial Data in R

In geospatial analysis, it is often necessary to obtain datasets from online sources for analysis. R provides a straightforward way to automate the process of downloading data from URLs and saving it to a specific path on your local machine. This can save time, ensure consistency, and allow seamless integration of data acquisition into oour analysis workflows.

Using the download.file() Function

# URL of the GADM data of San Marino
url <- "https://geodata.ucdavis.edu/gadm/gadm4.1/gpkg/gadm41_SMR.gpkg"

# Destination path to save the file
# provide the path where you want to save the geopackage and also change the name of the file
destfile <- "data/downloads/gadm41_SMR.gpkg"

# Download the file
download.file(url,
              destfile)

Automating Data Download

To simplify the process, we can wrap this functionality into a custom function that takes a URL and destination path as arguments. This can be particularly useful when managing multiple datasets.

Download one file at a time

In this subsection, we will create a function to download country-specific GeoPackage data from the GADM website.

get_gadm <- function(iso3 = NULL,
                     path = NULL) {
      
      # Construct the URL of the GADM data
      url <- 
        paste0("https://geodata.ucdavis.edu/gadm/gadm4.1/gpkg/gadm41_", iso3, ".gpkg")
      # Destination path to save the file
      destfile <- 
        paste0(path, "/", iso3, ".gpkg")
      # Download the file
      download.file(url,
                    destfile)
      # print message
      message("Download process completed.")
}

Now, we created a function named get_gadm() that takes the ISO3 code of the country of interest and the destination file path as arguments. We will use this function to download the GeoPackage containing the country polygon. Please ensure that you provide a valid ISO3 code and a proper file path to download the polygons; otherwise, a download error will occur.

# Example 1: Luxembourg
iso3 = "LUX"
path = "data/downloads/"
get_gadm(iso3, path)
Download process completed.
# Example 2: Cyprus
get_gadm(iso3 = "CYP",
         path = "data/downloads/")
Download process completed.

Multiple files downloading simultaneously

In this subsection, we will create a function to download GADM data for multiple countries simultaneously.

gadm_downloader <- function(iso3 = NULL,
                            path = NULL) {
  
  # Loop through each ISO3 code
  for (code in iso3) {
    
    # Construct the URL
    url <- paste0("https://geodata.ucdavis.edu/gadm/gadm4.1/gpkg/gadm41_", code, ".gpkg")
    # Destination path to save the file
    destfile <- 
      file.path(path, paste0(code, ".gpkg"))
    
    # Download the file
    message("Downloading GADM data for country: ", code)
    
    tryCatch({
      
      download.file(url, destfile)
      message("File for ", code, " downloaded successfully.")
      
    }, 
    error = function(e) {
      message("Failed to download file for ", code, ": ", e$message)
    })
  }
  
  message("Download process completed.")
}

Key Features of the Updated Function:

  • Handles Multiple Countries: Accepts a vector of ISO3 codes and processes them iteratively.
  • Error Handling: Uses tryCatch to gracefully handle download failures and continue with the next country.
  • Informative Messages: Provides feedback during the download process for each country.
# Example 3: Cyprus, San Marino, Luxembourg
# Define ISO3 codes and path
iso3_codes <- 
  c("CYP", "LUX", "SMR")
# Define output file path
output_path <- 
  "data/downloads/"

# Call the function
gadm_downloader(iso3 = iso3_codes,
                path = output_path)
Downloading GADM data for country: CYP
File for CYP downloaded successfully.
Downloading GADM data for country: LUX
File for LUX downloaded successfully.
Downloading GADM data for country: SMR
File for SMR downloaded successfully.
Download process completed.

Advantages of Automating Downloads:

  • Efficiency: Automates the tedious process of manually downloading files.
  • Reproducibility: Ensures that analyses can be reproduced with the same datasets.
  • Scalability: Handles multiple datasets with ease, particularly useful in batch processing.

By leveraging these techniques, we can integrate data acquisition seamlessly into our R scripts, ensuring an efficient and organized workflow for geospatial projects.

Computation Functions

In this section, we will create a function that computes zonal statistics based on the provided Area of Interest (AOI) and raster data. The zonal_operation function calculates zonal statistics for a given raster (spatial dataset) within a defined Area of Interest (AOI). It uses the idcol field to rasterize a polygon and then computes statistical summaries (like mean, sum, etc.) within each zone of the AOI.

zonal_operation <- function(aoi = NULL,
                            idcol = NULL,
                            rast = NULL,
                            opn = "mean") {
  
  # Convert AOI (sf) to SpatVector
  aoi_v <- vect(aoi)
  
  # Crop the raster to the AOI extent
  cropped_raster <- crop(rast, aoi_v)
  
  # Mask the raster using the AOI
  masked_raster <- mask(cropped_raster, aoi_v)
  
  # Rasterize the polygon using the ID column
  rasterized_aoi <- rasterize(aoi_v, masked_raster, field = idcol)
  
  # Compute zonal statistics
  zonal_stats <- zonal(masked_raster, rasterized_aoi, fun = opn, na.rm = TRUE)
  
  # Return zonal statistics as a data frame
  return(zonal_stats)
  
}

The function above takes four parameters:

  • aoi: The Area of Interest, typically a spatial polygon (e.g., a shapefile or spatial feature object).
  • idcol: The name of the column in the AOI data that will be used to create zones (for rasterization).
  • rast: The raster dataset on which zonal statistics will be computed.
  • opn: The operation to compute (e.g., “mean”, “sum”, etc.) over each zone. Default is “mean”.

As an example, let’s compute the total population in the year 2020 for different regions of Kanchanpur district.

# Load required libraries
library(sf)
library(terra)

# Load AOI polygon 
zones <- read_sf("data/vector/kanchanpur.gpkg")

# Load population count raster from year 2020
raster_data <- rast("data/raster/popCount_2020.tif")

# Set unique ID for the zonal operation
unique_ID <- "NAME"

# Operation to compute
method <- "sum"

# Call the function
zonal_operation(aoi = zones,
                idcol = unique_ID,
                rast = raster_data,
                opn = method)
                 NAME npl_ppp_2020_UNadj
1        BaisiBichawa         37900.0425
2            Beldandi         46565.3564
3            Chandani         72813.0097
4              Daijee         49223.9277
5         Dekhatbhuli         52221.7364
6             Dodhara         64436.5646
7             Jhalari         40823.8799
8              Kalika         97216.4754
9          Krishnapur         36368.5505
10           Laxmipur        277108.9353
11  MahendranagarN.P.         51835.0291
12            Parasan         38199.8677
13           Pipaladi         46773.8070
14    RaikawarBichawa         44571.7505
15     RampurBilaspur         48838.7719
16     RauteliBichawa         11581.3578
17 Royal Shuklaphanta           131.6414
18         Shankarpur         19211.7471
19            Sreepur         56755.7132
20               Suda         58257.6391
21     Tribhuwanbasti         37573.9453

In conclusion, mastering functions in R is essential for writing efficient, reusable, and organized code. Functions allow you to streamline complex tasks, avoid redundancy, and improve the readability and maintainability of your scripts. By understanding how to define and use functions, you can perform a wide range of data manipulation, statistical analysis, and visualization tasks more effectively. With the ability to build custom functions and leverage the vast array of built-in functions in R, you can significantly enhance your data analysis workflow, making your code more modular and adaptable to different challenges. Functions are a powerful tool that, once mastered, will elevate your R programming skills to the next level.

For this tutorial, this concludes the coverage of functions in R. If you would like to explore additional functions, examples, or need clarification on any of the steps covered, please visit the GitHub repository: R_tutorial and feel free to open an issue.


sessionInfo()
R version 4.4.0 (2024-04-24 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 22631)

Matrix products: default


locale:
[1] LC_COLLATE=English_Germany.utf8  LC_CTYPE=English_Germany.utf8   
[3] LC_MONETARY=English_Germany.utf8 LC_NUMERIC=C                    
[5] LC_TIME=English_Germany.utf8    

time zone: Europe/Berlin
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] terra_1.8-5     sf_1.0-19       workflowr_1.7.1

loaded via a namespace (and not attached):
 [1] jsonlite_1.8.8     compiler_4.4.0     promises_1.3.0     Rcpp_1.0.13       
 [5] stringr_1.5.1      git2r_0.33.0       callr_3.7.6        later_1.3.2       
 [9] jquerylib_0.1.4    yaml_2.3.10        fastmap_1.2.0      R6_2.5.1          
[13] classInt_0.4-10    knitr_1.48         tibble_3.2.1       units_0.8-5       
[17] rprojroot_2.0.4    DBI_1.2.3          bslib_0.8.0        pillar_1.9.0      
[21] rlang_1.1.4        utf8_1.2.4         cachem_1.1.0       stringi_1.8.4     
[25] httpuv_1.6.15      xfun_0.47          getPass_0.2-4      fs_1.6.4          
[29] sass_0.4.9         cli_3.6.3          magrittr_2.0.3     class_7.3-22      
[33] ps_1.8.1           grid_4.4.0         digest_0.6.36      processx_3.8.4    
[37] rstudioapi_0.16.0  lifecycle_1.0.4    vctrs_0.6.5        KernSmooth_2.23-22
[41] proxy_0.4-27       evaluate_0.24.0    glue_1.7.0         whisker_0.4.1     
[45] codetools_0.2-20   e1071_1.7-16       fansi_1.0.6        rmarkdown_2.28    
[49] httr_1.4.7         tools_4.4.0        pkgconfig_2.0.3    htmltools_0.5.8.1