Skip to content

Instantly share code, notes, and snippets.

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

Nicholas Tierney njtierney

👷‍♂️
Have some work availability from February 2026
View GitHub Profile
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    
vec <- c("", "", "a", "b", "")
dplyr::if_else(vec == "", NA, vec, NA)
#> [1] NA  NA  "a" "b" NA
dplyr::na_if(x = vec, "")
#> [1] NA  NA  "a" "b" NA

Created on 2025-07-16 with reprex v2.1.1

library(tidyverse)
str_detect_other_ish <- function(x) str_detect(x, "Other|Please explain")
  
vec <- c("Other", 
         "explain",
         "Other, explain",
         "Other country",
         "Other please explain",
         "Other, please explain",
library(stringr)
str_remove(str_extract("65. A question", "\\d+\\."), "\\.")
#> [1] "65"

str_extract_question_number <- function(text){
  str_remove(str_extract(text, "\\d+\\."), "\\.")
}

a_string <- "65. A question with other numbers, 123"