### Install phsmethods locally from zip Source: https://github.com/public-health-scotland/phsmethods/blob/master/README.md Installs the phsmethods package from a local zip file. This method is a fallback if direct GitHub installation is blocked by network security settings. Ensure to replace the placeholder with the actual file path. ```r remotes::install_local("/phsmethods-master.zip", upgrade = "never" ) ``` -------------------------------- ### Install phsmethods from GitHub Source: https://github.com/public-health-scotland/phsmethods/blob/master/README.md Installs the phsmethods package directly from its GitHub repository. Requires the 'remotes' package to be installed first. This method is useful for obtaining the latest development version. ```r install.packages("remotes") remotes::install_github("Public-Health-Scotland/phsmethods") ``` -------------------------------- ### Install phsmethods from CRAN Source: https://github.com/public-health-scotland/phsmethods/blob/master/README.md Installs the phsmethods package from the Comprehensive R Archive Network (CRAN). This is the recommended method for users within the PHS Posit Workbench environment. ```r install.packages("phsmethods") ``` -------------------------------- ### Access function documentation Source: https://github.com/public-health-scotland/phsmethods/blob/master/README.md Displays the help documentation for a specific function within the phsmethods package. This is useful for understanding function arguments, return values, and examples. ```r ?extract_fin_year ?format_postcode ``` -------------------------------- ### Load phsmethods package Source: https://github.com/public-health-scotland/phsmethods/blob/master/README.md Loads the phsmethods package into the current R session, making its functions available for use. This is a standard step after installing any R package. ```r library(phsmethods) ``` -------------------------------- ### Deprecated age_group function examples in R Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/rename.md Demonstrates the usage of the deprecated `age_group()` function in R for creating age groups from numeric vectors. It shows examples with different parameters like range, bin size, and factor conversion, highlighting that the function is defunct and users should use `create_age_groups()` instead. ```R expect_identical(age_group(c(4, 51, 21, 89), 0, 80, 10, as_factor = FALSE), c( "0-9", "50-59", "20-29", "80+")) ``` ```R expect_identical(age_group(c(8, 94, 44, 55, 14), 0, 90, 5, as_factor = TRUE), factor(c("5-9", "90+", "40-44", "55-59", "10-14"), levels = c("0-4", "5-9", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", "75-79", "80-84", "85-89", "90+"), ordered = TRUE)) ``` ```R expect_identical(age_group(c(81, 86, 33, 11), 4, 84, 3, as_factor = FALSE), c( "79-81", "82+", "31-33", "10-12")) ``` ```R expect_identical(age_group(c(0, 99, 1000, 5, 5), 5, 90, 5, as_factor = FALSE), c(NA, "90+", "90+", "5-9", "5-9")) ``` ```R expect_identical(age_group(10, as_factor = TRUE), factor(c("10-14"), levels = c( "0-4", "5-9", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", "75-79", "80-84", "85-89", "90+"), ordered = TRUE)) ``` ```R expect_error(age_group(c("1", "57", "apple", "12"), as_factor = FALSE)) ``` ```R expect_error(age_group(c("26", "9", "78", "81"), as_factor = FALSE)) ``` -------------------------------- ### Deprecated fin_year function examples in R Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/rename.md Illustrates the use of the deprecated `fin_year()` function in R for converting dates into financial year strings. It shows various date formats and expected outputs, emphasizing that this function is defunct and `extract_fin_year()` should be used instead. Includes examples with valid dates, NA values, and error cases for invalid inputs. ```R expect_equal(fin_year(as.Date("20120331", "%Y%m%d")), "2011/12") ``` ```R expect_equal(fin_year(as.Date("20120401", "%Y%m%d")), "2012/13") ``` ```R expect_equal(fin_year(as.POSIXct("20190104", format = "%Y%m%d")), "2018/19") ``` ```R expect_equal(fin_year(as.Date("17111993", "%d%m%Y")), "1993/94") ``` ```R expect_equal(fin_year(as.Date("19980404", "%Y%m%d")), "1998/99") ``` ```R expect_equal(fin_year(as.Date("21-Jan-2017", "%d-%B-%Y")), "2016/17") ``` ```R expect_equal(fin_year(as.POSIXct("20181401", format = "%Y%d%m")), "2017/18") ``` ```R expect_equal(fin_year(lubridate::dmy(29102019)), "2019/20") ``` ```R expect_error(fin_year("28102019")) ``` ```R expect_error(fin_year("28-Oct-2019")) ``` ```R expect_error(fin_year(as.numeric("28102019"))) ``` ```R expect_error(fin_year(as.factor("28-Oct-2019"))) ``` ```R expect_equal(fin_year(c(lubridate::dmy(5012020), NA)), c("2019/20", NA)) ``` -------------------------------- ### List Files and Sizes in Directory using R Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/UNIX/file_size.md This R code snippet demonstrates how to use the `file_size` function to list all files in a given directory and display their names and sizes. It's useful for quick file inventory. ```r file_size(test_path("files")) ``` -------------------------------- ### Represent Proportions as Percentages Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The as_percent function creates a lightweight S3 class for displaying proportions as percentages. It preserves the underlying numeric values for calculations, supports rounding, and allows for mathematical operations and custom formatting. ```r library(phsmethods) library(dplyr) # Convert proportions to percentages as_percent(seq(0, 1, 0.1)) #> [1] "0%" "10%" "20%" "30%" "40%" "50%" "60%" "70%" "80%" "90%" "100%" # Underlying values are preserved p <- as_percent(0.000567) p #> [1] "0.06%" as.double(p) #> [1] 0.000567 # Rounding operations p <- as_percent(15.56 / 100) round(p) #> [1] "16%" round(p, digits = 1) #> [1] "15.6%" # Math operations work naturally 10 * as_percent(c(0, 0.5, 2)) #> [1] "0%" "500%" "2,000%" as_percent(0.1) + as_percent(0.2) #> [1] "30%" # Summary statistics mean(as_percent(c(0.1, 0.2, 0.3))) #> [1] "20%" # Use in data analysis starwars %>% count(eye_color) %>% mutate(perc = as_percent(n / sum(n))) %>% arrange(desc(perc)) %>% head() #> # A tibble: 6 x 3 #> eye_color n perc #> #> 1 brown 21 24.14% #> 2 blue 19 21.84% #> 3 yellow 11 12.64% #> 4 black 10 11.49% #> 5 orange 8 9.2% #> 6 red 5 5.75% # Custom formatting format(as_percent(2.674 / 100), digits = 2, symbol = " (%)") #> [1] "2.67 (%)" ``` -------------------------------- ### Create Age Groups using R Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `create_age_groups()` function categorizes numerical ages into predefined or custom age bands. It defaults to European Standard Population bands and can return results as character strings or ordered factors. Dependencies include `phsmethods` and `dplyr`. ```r library(phsmethods) library(dplyr) age <- c(54, 7, 77, 1, 26, 101) # Default 5-year age groups (0-90+) create_age_groups(age) #> [1] "50-54" "5-9" "75-79" "0-4" "25-29" "90+" # Custom age groups (10-year bands up to 80+) create_age_groups(age, from = 0, to = 80, by = 10) #> [1] "50-59" "0-9" "70-79" "0-9" "20-29" "80+" # Final group adjusts to multiple of 'by' create_age_groups(age, from = 0, to = 65, by = 10) #> [1] "50-59" "0-9" "60+" "0-9" "20-29" "60+" # Return as ordered factor for proper sorting create_age_groups(age, as_factor = TRUE) #> [1] 50-54 5-9 75-79 0-4 25-29 90+ #> 18 Levels: 0-4 < 5-9 < 10-14 < 15-19 < 20-24 < 25-29 < ... < 90+ # Use in data analysis tibble(age = c(23, 45, 67, 12, 89, 34)) %>% mutate(age_group = create_age_groups(age)) %>% count(age_group) #> # A tibble: 6 x 2 #> age_group n #> #> 1 10-14 1 #> 2 20-24 1 #> 3 30-34 1 #> 4 45-49 1 #> 5 65-69 1 #> 6 85-89 1 ``` -------------------------------- ### Assign Dates to Calendar Quarters Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The qtr(), qtr_end(), qtr_next(), and qtr_prev() functions are used to assign dates to specific calendar quarters. They support both long and short format outputs and can be integrated into data analysis pipelines. ```r library(phsmethods) library(lubridate) x <- dmy(c(26032012, 04052012, 23092012)) # Current quarter qtr(x) #> [1] "January to March 2012" "April to June 2012" #> [3] "July to September 2012" # Short format qtr(x, format = "short") #> [1] "Jan-Mar 2012" "Apr-Jun 2012" "Jul-Sep 2012" # Last month of quarter qtr_end(x) #> [1] "March 2012" "June 2012" "September 2012" qtr_end(x, format = "short") #> [1] "Mar 2012" "Jun 2012" "Sep 2012" # Next quarter qtr_next(x) #> [1] "April to June 2012" "July to September 2012" #> [3] "October to December 2012" # Previous quarter qtr_prev(x, format = "short") #> [1] "Oct-Dec 2011" "Jan-Mar 2012" "Apr-Jun 2012" # Use in reporting library(dplyr) reports <- tibble( report_date = ymd(c("2023-02-15", "2023-05-20", "2023-08-10", "2023-11-25")) ) reports %>% mutate( quarter = qtr(report_date, format = "short"), next_quarter = qtr_next(report_date, format = "short") ) #> # A tibble: 4 x 3 #> report_date quarter next_quarter #> #> 1 2023-02-15 Jan-Mar 2023 Apr-Jun 2023 #> 2 2023-05-20 Apr-Jun 2023 Jul-Sep 2023 #> 3 2023-08-10 Jul-Sep 2023 Oct-Dec 2023 #> 4 2023-11-25 Oct-Dec 2023 Jan-Mar 2024 ``` -------------------------------- ### Format Multiple Postcodes with Warnings (R) Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/format_postcode.md Illustrates the format_postcode function with a vector of postcodes in R. It shows how mixed valid and invalid inputs are processed, including case conversion and conversion of non-adhering postcodes to NA, accompanied by warnings. ```r format_postcode(c("DG98BS", "dg98b")) ``` -------------------------------- ### Filter Files by Extension using R Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/UNIX/file_size.md This R code snippet shows how to filter the output of the `file_size` function to only include files with specific extensions, such as '.xlsx'. This is helpful for targeting particular file types. ```r file_size(test_path("files"), "xlsx?") ``` -------------------------------- ### Demonstrate Deprecated Postcode Function Usage and Errors Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/rename.md This snippet showcases various ways the deprecated 'postcode' function was used, including different formats and input types. It also illustrates the expected error messages indicating the function's deprecation and recommending the use of 'format_postcode'. ```r expect_equal(stringr::str_length(postcode("G26QE", format = "pc7")), 7) ``` ```r expect_equal(stringr::str_length(postcode("G26QE", format = "pc8")), 6) ``` ```r expect_equal(stringr::str_length(postcode(c("KA89NB", "PA152TY"), format = "pc7")), c(7, 7)) ``` ```r expect_equal(stringr::str_length(postcode(c("KA89NB", "PA152TY"), format = "pc8")), c(7, 8)) ``` ```r expect_equal(postcode("G36RB"), "G3 6RB") ``` ```r expect_equal(postcode("G432XR"), "G43 2XR") ``` ```r expect_equal(postcode("DG29BA"), "DG2 9BA") ``` ```r expect_equal(postcode("FK101RY"), "FK101RY") ``` ```r expect_equal(postcode("E1W3TJ"), "E1W 3TJ") ``` ```r expect_equal(postcode("EC1Y8SE"), "EC1Y8SE") ``` ```r input_hampden <- c("G429BA", "g429ba", "G42 9BA", "G 4 2 9 B A", "G429b a") expect_true(length(unique(postcode(input_hampden))) == 1) ``` ```r expect_equal(unique(postcode(input_hampden)), "G42 9BA") ``` ```r expect_true(is.na(suppressWarnings(postcode("G2?QE")))) ``` ```r expect_warning(postcode(c("G207AL", "G2O07AL"))) ``` ```r expect_equal(suppressWarnings(postcode(c("EH7 5QG", NA, "EH11 2NL", "EH5 2HF*"))), c("EH7 5QG", NA, "EH112NL", NA)) ``` ```r input_dens <- c("Dd37Jy", "DD37JY", "D d 337JY") expect_length(capture_warnings(postcode(input_dens)), 2) ``` ```r input_pittodrie <- c("ab245qh", NA, "ab245q", "A B245QH") expect_length(capture_warnings(postcode(input_pittodrie)), 3) ``` ```r expect_warning(postcode("g2"), "^1") ``` ```r expect_warning(postcode(c("DG98BS", "dg98b")), "^1") ``` ```r expect_warning(postcode(c("KY1 1RZ", "ky1rz", "KY11 R", "KY11R!")), "^3") ``` ```r expect_warning(postcode(c("ML53RB", NA, "ML5", "???", 53, as.factor("ML53RB"))), "^4") ``` -------------------------------- ### Generate Financial Year Data (R) Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/extract_fin_year.md This R code snippet generates a data frame containing financial years, the first and last dates of each year, and the number of days within that year. It utilizes the `lubridate` package for date manipulation and `dplyr` for data summarization. The `extract_fin_year` function is assumed to be defined elsewhere and is crucial for converting dates into financial year strings. ```r start <- lubridate::make_date(1999, 4, 1) end <- lubridate::make_date(2100, 3, 31) dates <- seq(start, end, by = "day") df <- data.frame(date = dates, fin_year = extract_fin_year(dates)) dplyr::summarise(df, first_date = min(date), last_date = max(date), days = dplyr::n(), .by = fin_year) ``` -------------------------------- ### Format Postcodes with Invalid Handling Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The format_postcode function standardizes UK postcodes, returning NA for invalid entries. It can suppress warnings in production using the 'quiet' argument. ```r library(phsmethods) # Invalid postcodes return NA with warning format_postcode(c("G26QE", "INVALID", "12345")) #> [1] "G2 6QE" NA NA # Suppress warnings in production with quiet = TRUE format_postcode(c("G26QE", "INVALID"), quiet = TRUE) #> [1] "G2 6QE" NA # Use in pipeline df <- tibble(postcode = c("G429BA", "G207AL", "DD37JY", "DG98BS")) df %>% mutate(postcode_formatted = format_postcode(postcode)) #> # A tibble: 4 x 2 #> postcode postcode_formatted #> #> 1 G429BA G42 9BA #> 2 G207AL G20 7AL #> 3 DD37JY DD3 7JY #> 4 DG98BS DG9 8BS ``` -------------------------------- ### Format UK Postcodes using R Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `format_postcode()` function standardizes UK postcodes to either pc7 (7-character fixed width) or pc8 (variable width with a single space before the last three characters) format. It handles variations in input casing and spacing. Dependencies include `phsmethods` and `dplyr`. ```r library(phsmethods) library(dplyr) # Basic formatting - pc7 format (default) format_postcode("G26QE") #> [1] "G2 6QE" format_postcode(c("KA89NB", "PA152TY")) #> [1] "KA8 9NB" "PA152TY" # pc8 format - single space before last 3 characters format_postcode(c("KA89NB", "PA152TY"), format = "pc8") #> [1] "KA8 9NB" "PA15 2TY" # Handles lowercase and existing spaces format_postcode(c("eh1 1aa", "G2 6QE", "pa15 2ty")) #> [1] "EH1 1AA" "G2 6QE" "PA152TY" ``` -------------------------------- ### Pad CHI Numbers with phsmethods Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `chi_pad()` function adds a leading zero to nine-digit CHI numbers that are missing it, which is useful when importing data from systems that strip leading zeros. It can process vectors of CHI numbers, applying padding only to valid nine-digit numeric strings. The function can be combined with `chi_check()` for validation after padding. ```r library(phsmethods) # Pad nine-digit CHI numbers chi_pad("101011237") #> [1] "0101011237" # Works on vectors - only pads 9-digit numeric strings chi_pad(c("101011237", "101201234", "0101011237", "12345", NA)) #> [1] "0101011237" "0101201234" "0101011237" "12345" NA # Combine with validation library(dplyr) tibble(chi = c("101011237", "0101336489")) %>% mutate( chi_padded = chi_pad(chi), valid = chi_check(chi_padded) ) #> # A tibble: 2 x 3 #> chi chi_padded valid #> #> 1 101011237 0101011237 Valid CHI #> 2 0101336489 0101336489 Valid CHI ``` -------------------------------- ### Format Diverse Postcode Inputs with Warnings (R) Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/format_postcode.md Shows the behavior of format_postcode in R when given a diverse set of inputs, including valid, invalid, NA, and different data types (numeric, factor). It highlights the function's robustness in converting various inputs to NA when they don't conform to the UK postcode format, while issuing warnings. ```r format_postcode(c("ML53RB", NA, "ML5", "???", 53, as.factor("ML53RB"))) ``` -------------------------------- ### Format UK Postcode with Warnings (R) Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/format_postcode.md Demonstrates the format_postcode function in R, showing how it handles single invalid postcodes and generates warnings for case inconsistencies and format non-adherence. Non-standard postcodes are converted to NA. ```r format_postcode("g2") ``` -------------------------------- ### Format Postcodes with Quiet Option (R) Source: https://github.com/public-health-scotland/phsmethods/blob/master/tests/testthat/_snaps/format_postcode.md Compares the output of format_postcode in R with the `quiet` argument set to TRUE and FALSE. When `quiet` is TRUE, warnings for case conversion and format non-adherence are suppressed. When `quiet` is FALSE, warnings are displayed, detailing issues like lowercase letters and non-standard formats. ```r format_postcode(c("KY1 1RZ", "ky1rz", "KY11 R", "KY11R!"), quiet = TRUE) format_postcode(c("KY1 1RZ", "ky1rz", "KY11 R", "KY11R!"), quiet = FALSE) ``` -------------------------------- ### Calculate Age Between Dates using R Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `age_calculate()` function computes the age between two dates in years or months, correctly handling leap years. It can also return fractional ages if `round_down` is set to `FALSE`. Dependencies include `phsmethods` and `lubridate`. ```r library(phsmethods) library(lubridate) # Basic age calculation birth_date <- ymd("2020-02-29") end_date <- ymd("2022-02-21") age_calculate(birth_date, end_date) #> [1] 1 # Age in months age_calculate(birth_date, end_date, units = "months") #> [1] 23 # Leap year handling - age increases on March 1st leap1 <- ymd("2020-02-29") leap2 <- ymd("2022-02-28") leap3 <- ymd("2022-03-01") age_calculate(leap1, leap2) #> [1] 1 age_calculate(leap1, leap3) #> [1] 2 # Don't round down for fractional ages age_calculate(birth_date, end_date, round_down = FALSE) #> [1] 1.98 # Calculate ages for multiple records library(dplyr) patients <- tibble( dob = ymd(c("1990-05-15", "1985-12-01", "2000-03-20")), visit_date = ymd(c("2023-06-01", "2023-06-01", "2023-06-01")) ) patients %>% mutate(age = age_calculate(dob, visit_date)) #> # A tibble: 3 x 3 #> dob visit_date age #> #> 1 1990-05-15 2023-06-01 33 #> 2 1985-12-01 2023-06-01 37 #> 3 2000-03-20 2023-06-01 23 ``` -------------------------------- ### Extract Financial Year from Dates using R Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `extract_fin_year()` function converts dates into the PHS financial year format (YYYY/YY). It correctly handles the April 1st to March 31st financial year definition. Dependencies include `phsmethods`, `lubridate`, and `dplyr`. ```r library(phsmethods) library(lubridate) library(dplyr) # Basic usage x <- dmy(c(21012017, 04042017, 17112017)) extract_fin_year(x) #> [1] "2016/17" "2017/18" "2017/18" # Dates in March belong to previous financial year march_date <- ymd("2023-03-15") april_date <- ymd("2023-04-15") extract_fin_year(march_date) #> [1] "2022/23" extract_fin_year(april_date) #> [1] "2023/24" # Use in pipeline admissions <- tibble( admission_date = ymd(c("2022-01-15", "2022-04-01", "2022-12-25", "2023-03-31")) ) admissions %>% mutate(fin_year = extract_fin_year(admission_date)) #> # A tibble: 4 x 2 #> admission_date fin_year #> #> 1 2022-01-15 2021/22 #> 2 2022-04-01 2022/23 #> 3 2022-12-25 2022/23 #> 4 2023-03-31 2022/23 ``` -------------------------------- ### Match Scottish Geography Codes to Area Names Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The match_area function translates Scottish geography codes (like Data Zones, Health Boards, Council Areas) into their corresponding human-readable area names using an internal lookup dataset. It handles single or multiple codes and special codes for residency status. ```r library(phsmethods) library(dplyr) # Single geography code match_area("S20000010") #> [1] "Glasgow City" # Multiple geography codes match_area(c("S08000020", "S12000013")) #> [1] "NHS Grampian" "Na h-Eileanan Siar" # Works with various geography types codes <- c( "S02000656", # Data Zone "S02001042", # Data Zone "S08000020", # Health Board "S12000013" # Council Area ) match_area(codes) #> [1] "Kelvindale" "Maryhill" #> [3] "NHS Grampian" "Na h-Eileanan Siar" # Special codes for non-standard residency match_area(c("RA2701", "RA2702", "RA2703", "RA2704")) #> [1] "No Fixed Abode" "Rest of UK (Outside Scotland)" #> [3] "Outside the UK" "Unknown Residency" # Use in pipeline df <- tibble(code = c("S02000656", "S02001042", "S08000020", "S12000013")) df %>% mutate(area_name = match_area(code)) #> # A tibble: 4 x 2 #> code area_name #> #> 1 S02000656 Kelvindale #> 2 S02001042 Maryhill #> 3 S08000020 NHS Grampian #> 4 S12000013 Na h-Eileanan Siar ``` -------------------------------- ### Extract Age from CHI Number using R Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `age_from_chi()` function calculates a patient's age using their CHI number. It can take a reference date and age constraints to resolve century ambiguity. Dependencies include the `phsmethods` and `dplyr` packages. ```r library(phsmethods) library(dplyr) library(tibble) # Basic usage - age as of today age_from_chi("0101336489") #> [1] 92 # With reference date and age constraints data <- tibble( chi = c("0101336489", "0101405073", "0101625707"), discharge_date = as.Date(c("1950-01-01", "2000-01-01", "2020-01-01")) ) # Calculate age at discharge with expected age range data %>% mutate(age_at_discharge = age_from_chi( chi, ref_date = discharge_date, min_age = 0, max_age = 120 )) #> # A tibble: 3 x 3 #> chi discharge_date age_at_discharge #> #> 1 0101336489 1950-01-01 17 #> 2 0101405073 2000-01-01 59 #> 3 0101625707 2020-01-01 57 # For adult patients only data %>% mutate(age = age_from_chi(chi, min_age = 18, max_age = 65)) ``` -------------------------------- ### Extract Date of Birth from CHI Number with phsmethods Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `dob_from_chi()` function extracts the date of birth from a CHI number. Since CHI numbers use 2-digit years, optional `min_date` and `max_date` constraints can be provided to resolve century ambiguity, often using an admission date as the `max_date`. ```r library(phsmethods) library(dplyr) library(tibble) # Basic usage dob_from_chi("0101336489") #> [1] "1933-01-01" # With date constraints to resolve century ambiguity data <- tibble( chi = c("0101336489", "0101405073", "0101625707"), admission_date = as.Date(c("1950-01-01", "2000-01-01", "2020-01-01")) ) # Without constraints - may produce NA for ambiguous dates data %>% mutate(dob = dob_from_chi(chi)) # With constraints - uses admission date to resolve century data %>% mutate(dob = dob_from_chi( chi, min_date = as.Date("1900-01-01"), max_date = admission_date )) #> # A tibble: 3 x 3 #> chi admission_date dob #> #> 1 0101336489 1950-01-01 1933-01-01 #> 2 0101405073 2000-01-01 1940-01-01 #> 3 0101625707 2020-01-01 1962-01-01 ``` -------------------------------- ### Extract Sex from CHI Number with phsmethods Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `sex_from_chi()` function extracts patient sex from a CHI number, using the ninth digit (odd for male, even for female). It can return integers (1 for male, 2 for female), custom values, or factors with labels. The function handles vectors and can be used within dplyr pipelines. ```r library(phsmethods) library(dplyr) # Basic usage - returns integer (1 = male, 2 = female) sex_from_chi("0101011237") #> [1] 1 sex_from_chi(c("0101011237", "0101336489", NA)) #> [1] 1 2 NA # Return custom values sex_from_chi(c("0101011237", "0101336489"), male_value = "M", female_value = "F") #> [1] "M" "F" # Return as factor with labels sex_from_chi(c("0101011237", "0101336489", NA), as_factor = TRUE) #> [1] Male Female #> Levels: Male Female # Use in pipeline df <- tibble(chi = c("0101011237", "0101336489", NA)) df %>% mutate(sex = sex_from_chi(chi, as_factor = TRUE)) #> # A tibble: 3 x 2 #> chi sex #> #> 1 0101011237 Male #> 2 0101336489 Female #> 3 NA NA ``` -------------------------------- ### Validate CHI Numbers with phsmethods Source: https://context7.com/public-health-scotland/phsmethods/llms.txt The `chi_check()` function validates Community Health Index (CHI) numbers by verifying their format, length, date validity, and checksum. It returns descriptive messages indicating validity or the reason for invalidity. This function can process individual CHI numbers or vectors of numbers and integrates with dplyr pipelines for data frame manipulation. ```r library(phsmethods) library(dplyr) # Check individual CHI numbers chi_check("0101011237") #> [1] "Valid CHI" chi_check("3201201234") #> [1] "Invalid date" # Validate a vector of CHI numbers chi_numbers <- c("0101011237", "123456789", "12345678900", "010120123?", NA, "") chi_check(chi_numbers) #> [1] "Valid CHI" "Too few characters" #> [3] "Too many characters" "Invalid character(s) present" #> [5] "Missing (NA)" "Missing (Blank)" # Use in a data pipeline df <- tibble(chi = c("3213201234", "123456789", "12345678900", "010120123?", NA)) df %>% mutate(validity = chi_check(chi)) #> # A tibble: 5 x 2 #> chi validity #> #> 1 3213201234 Invalid date #> 2 123456789 Too few characters #> 3 12345678900 Too many characters #> 4 010120123? Invalid character(s) present #> 5 NA Missing (NA) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.