Skip to content

Instantly share code, notes, and snippets.

View njtierney's full-sized avatar
👷‍♂️
Have some work availability from April 2026

Nicholas Tierney njtierney

👷‍♂️
Have some work availability from April 2026
View GitHub Profile
Sys.setenv(rndseed = 1234)

x <- rnorm(5)

Sys.setenv(rndseed = 1234)

y <- rnorm(5)

x
# Create a SpatRaster from a file
library(bench)
library(terra)
#> terra 1.8.93
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)

drv <- terra::as.data.frame(r)
# based on RO water
gypsum <- function(litres) litres * (0.56 / 14)
ca_cl <- function(litres) litres * (2.66 / 14)
epsom <- function(litres) litres * (0.84 / 14)
acid <- function(litres) litres * (2 / 14)

gypsum(7)
#> [1] 0.28
ca_cl(7)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidyverse)
some_logicals <- function(n){
  sample(c(TRUE, FALSE, NA), replace = TRUE, size = n)
}

dat_lgl <- tibble(
  x = some_logicals(10),
  y = some_logicals(10),
 z = some_logicals(10)
library(tidyverse)
dat <- tibble(response = c("2;3", "1;3", "1;4", "1;2", "3;4;5", "1;4;5"))
dat
#> # A tibble: 6 × 1
#>   response
#>   <chr>   
#> 1 2;3     
#> 2 1;3     
#> 3 1;4     
library(tidyverse)

# overall, the approach is to try and make a function that takes in a vector
# and returns some output, in this case a list
create_dummies <- function(vec, col_name = NULL) {
  # %||% is the "null pipe", this is the equivalent of:
  # if (is.null(col_name)){
  #   col_name <- deparse(substitute(vec))
  # }
library(tidyverse)
vec <- c(
  NA,
  "0, Low (1-3) | 1, Moderate (4-6) | 2, High (7-10) | 3, Very High (11-14)",
  "0, Low to Moderate | 1, High to Very High",
  "0, No (0) | 1, Low (1-3) | 2, Moderate (4-9) | 3, High  (10-15)",
  "0, No (0) | 1, Low  (1-3) | 2, Moderate-high  (4-9)",
  "0, No (0) | 1, Low  (1-3) | 2, Moderate  (4-8) | 3, High  (9-13)",
  "0, No (0) | 1, Low  (1-3) | 2, Moderate-high  (4-10)"
library(tidyverse)
dat <- tibble(
  variable = c("k2", "k2", "k4", "k5", "k4")
)

dat
#> # A tibble: 5 × 1
#>   variable
#>   <chr>   
library(tidyverse)
dat <- tibble(
  x = as.character(c("NA", "NA", 1, 2)),
  y = as.character(c(1, 2, "NA", "NA"))
)

dat
#> # A tibble: 4 × 2
#>   x     y