### Install phsmethods from GitHub Source: https://public-health-scotland.github.io/phsmethods/index 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 locally from a zip file Source: https://public-health-scotland.github.io/phsmethods/index Installs the phsmethods package from a local zip file. This method is a workaround for network security settings that may prevent direct GitHub installation. Replace '' with the actual path to the downloaded zip file. ```r remotes::install_local("/phsmethods-master.zip", upgrade = "never" ) ``` -------------------------------- ### Install phsmethods from PHS Posit Package Manager Source: https://public-health-scotland.github.io/phsmethods/index Installs the phsmethods package from the PHS Posit Package Manager. This is the recommended method for users within the PHS environment. ```r install.packages("phsmethods") ``` -------------------------------- ### Load phsmethods package Source: https://public-health-scotland.github.io/phsmethods/index Loads the phsmethods package into the R session, making its functions available for use. This is a standard step after installing any R package. ```r library(phsmethods) ``` -------------------------------- ### Access function documentation in phsmethods Source: https://public-health-scotland.github.io/phsmethods/index Accesses the help documentation for specific functions within the phsmethods package. Typing a question mark followed by the function name in the RStudio console will display its usage, arguments, and examples. ```r ?extract_fin_year ?format_postcode ``` -------------------------------- ### Calculate age with event date as ref_date and min/max age limits using age_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This example calculates age using `age_from_chi` with the `event_date` as the reference date, and applies both `min_age` and `max_age` constraints. Ages outside this range will be set to NA. ```r data %> mutate(age = age_from_chi( chi, ref_date = event_date, min_age = 60, max_age = 120 )) ``` -------------------------------- ### Calculate age at a fixed reference date using age_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This example demonstrates calculating age using `age_from_chi` with a specific reference date (`as.Date("2016-01-01")`) using the `ref_date` argument. This allows for age calculation at a historical point in time. ```r data %> mutate(age = age_from_chi(chi, ref_date = as.Date("2016-01-01"))) ``` -------------------------------- ### Extract DOB with fixed min_date and event_date as max_date using dob_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This example shows how to extract a date of birth using `dob_from_chi` with both a fixed minimum date (`as.Date("1915-01-01")`) and the `event_date` as the maximum date. This provides more control over the date range for DOB extraction. ```r data_dob <- data %> mutate(dob = dob_from_chi( chi, max_date = event_date, min_date = as.Date("1915-01-01") )) ``` -------------------------------- ### Clean and Validate CHI Numbers in a Data Frame with dplyr Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This example demonstrates cleaning and validating CHI numbers within a data frame using dplyr and phsmethods. It uses chi_pad() to fix leading zeros and chi_check() to add a validity column. The output shows the original data, the cleaned data with validity checks, and a frequency count of validation issues. ```r library(dplyr) data <- tibble(chi = c( "0211165794", "9999999999", "402070763", "00402070763", "0101010000", "Missing CHI", NA, "" )) fixed_data <- data %>% mutate(chi = chi_pad(chi)) checked_data <- fixed_data %>% mutate(valid_chi = chi_check(chi)) checked_data #> # A tibble: 8 × 2 #> chi valid_chi #> #> 1 "0211165794" Valid CHI #> 2 "9999999999" Invalid date #> 3 "0402070763" Valid CHI #> 4 "00402070763" Too many characters #> 5 "0101010000" Invalid checksum #> 6 "Missing CHI" Invalid character(s) present #> 7 NA Missing (NA) #> 8 "" Missing (Blank) fixed_data %>% count(valid_chi = chi_check(chi), sort = TRUE) #> # A tibble: 7 × 2 #> valid_chi n #> #> 1 Valid CHI 2 #> 2 Invalid character(s) present 1 #> 3 Invalid checksum 1 #> 4 Invalid date 1 #> 5 Missing (Blank) 1 #> 6 Missing (NA) 1 #> 7 Too many characters 1 ``` -------------------------------- ### Calculate Age Between Dates in R Source: https://public-health-scotland.github.io/phsmethods/reference/age_calculate Calculates the age between a start and end date in specified units (years or months). It leverages the 'lubridate' package for date operations. The function can round down the age to the nearest whole number. It accepts Date, POSIXct, or POSIXlt class inputs for start and end dates. ```R library(lubridate) birth_date <- lubridate::ymd("2020-02-29") end_date <- lubridate::ymd("2022-02-21") age_calculate(birth_date, end_date) #> [1] 1 age_calculate(birth_date, end_date, units = "months") #> [1] 23 # If the start day is leap day (February 29th), age increases on 1st March # every year. leap1 <- lubridate::ymd("2020-02-29") leap2 <- lubridate::ymd("2022-02-28") leap3 <- lubridate::ymd("2022-03-01") age_calculate(leap1, leap2) #> [1] 1 age_calculate(leap1, leap3) #> [1] 2 ``` -------------------------------- ### Simplify Percentage Formatting in R Source: https://public-health-scotland.github.io/phsmethods/news/index Demonstrates how to use the `as_percent()` function from the phsmethods package to simplify percentage formatting in R. It contrasts the new method with the traditional approach, highlighting the ease of use and the ability to perform mathematical operations on percent vectors. ```R x <- c(0.25, 0.5, 0.75) paste0(x * 100, "%”) ## [1] "25%" "50%" "75%" x <- c(0.25, 0.5, 0.75) as_percent(x) ## [1] "25%" "50%" "75%" p <- as_percent(0.000567) p ## [1] "0.06%" as.double(p) # Under-the-hood nothing is modified ## [1] 0.000567 ``` -------------------------------- ### Create a percent vector using as_percent() in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent Demonstrates the creation of a '' vector from a numeric value using the `as_percent()` function. It shows how the output is formatted as a percentage string and how the underlying numeric value is preserved with an attribute for rounding. ```r (p <- as_percent(0.055)) #> [1] "5.5%" unclass(p) #> [1] 0.055 #> attr(," .digits") #> [1] 2 print(p) #> [1] "5.5%" as.character(p) #> [1] "5.5%" format(p) #> [1] "5.5%" ``` -------------------------------- ### Format Percent Summary Data into a Table with flextable in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent This code demonstrates formatting a data frame with percentage summaries ('perc_summary') into a table using the 'qflextable()' function from the 'flextable' package, providing an alternative to kable for enhanced table styling. ```R library(flextable) qflextable(perc_summary) ``` -------------------------------- ### Configure Git for GitHub Integration in R Source: https://public-health-scotland.github.io/phsmethods/index This R code snippet configures RStudio to link with your GitHub account using the 'usethis' package. This is a prerequisite for making contributions to the phsmethods repository via Git. ```r usethis::edit_git_config() ``` -------------------------------- ### Create and Format Percent Vectors in R Source: https://public-health-scotland.github.io/phsmethods/reference/percent The `as_percent` function creates a lightweight S3 class for pretty printing proportions as percentages, removing the need for character vectors. It supports custom rounding and formatting, and integrates with standard R functions like `round()`, `signif()`, `floor()`, and `ceiling()`. The class also allows for basic arithmetic operations and displays nicely in data frames. ```R as_percent(seq(0, 1, 0.1)) #> [1] "0%" "10%" "20%" "30%" "40%" "50%" "60%" "70%" "80%" "90%" #> [11] "100%" p <- as_percent(15.56 / 100) round(p) #> [1] "16%" round(p, digits = 1) #> [1] "15.6%" p2 <- as_percent(0.0005) signif(p2, 2) #> [1] "0.05%" floor(p2) #> [1] "0%" ceiling(p2) #> [1] "1%" 10 * as_percent(c(0, 0.5, 2)) #> [1] "0%" "500%" "2,000%" as_percent(c(0, 0.5, 2)) * 10 #> [1] "0%" "500%" "2,000%" as_percent(0.1) + as_percent(0.2) #> [1] "30%" format(as_percent(2.674 / 100), digits = 2, symbol = " (%)") #> [1] "2.67 (%)" library(dplyr) starwars %>% count(eye_color) %>% mutate(perc = as_percent(n / sum(n))) %>% arrange(desc(perc)) %>% mutate(perc_rounded = round(perc)) #> # A tibble: 15 × 4 #> eye_color n perc perc_rounded #> #> 1 brown 21 24.14% 24% #> 2 blue 19 21.84% 22% #> 3 yellow 11 12.64% 13% #> 4 black 10 11.49% 11% #> 5 orange 8 9.20% 9% #> 6 red 5 5.75% 6% #> 7 hazel 3 3.45% 3% #> 8 unknown 3 3.45% 3% #> 9 blue-gray 1 1.15% 1% #> 10 dark 1 1.15% 1% #> 11 gold 1 1.15% 1% #> 12 green, yellow 1 1.15% 1% #> 13 pink 1 1.15% 1% #> 14 red, blue 1 1.15% 1% #> 15 white 1 1.15% 1% ``` -------------------------------- ### Format Percent Summary Data into a Table with kable in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent This snippet shows how to format a data frame containing percentage summaries ('perc_summary') into a nicely formatted table using the 'kable()' function from the 'knitr' package. ```R library(knitr) kable(perc_summary) ``` -------------------------------- ### Perform mathematical operations with percent vectors in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent Demonstrates arithmetic operations (addition, subtraction, multiplication, division) with '' vectors. A helper function `percent()` is defined to easily create percentage values from proportions, enabling intuitive mathematical calculations. ```r # Helper to create literal percentages percent <- function(x) { as_percent(x / 100) } percent(50) + percent(25) # = 50% + 25% = 75% #> [1] "75%" percent(50) - percent(25) # = 50% - 25% = 25% #> [1] "25%" percent(50) * percent(25) # = 50% * (1/4) = 12.5% #> [1] "12.5%" percent(50) / percent(25) # = 50% / (1/4) = 200% #> [1] "200%" ``` -------------------------------- ### Integrate percent vectors with dplyr in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent Demonstrates the use of '' vectors within a 'dplyr' workflow in R. It shows how to count occurrences of a variable, calculate proportions, convert them to '' vectors using `as_percent()`, and add this as a new column to a tibble. ```r 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 species <- starwars |> count(species, sort = TRUE) |> mutate(perc = as_percent(n / sum(n), digits = 1)) ``` -------------------------------- ### Prepare Data for Percent Vector Visualization with ggplot2 in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent This code prepares the 'iris' dataset for visualization by counting species, calculating proportions, and converting them to percent vectors using 'as_percent()'. The resulting 'gg_data' tibble is then displayed. ```R library(ggplot2) gg_data <- iris | as_tibble() | count(Species) | mutate( prop = n / sum(n), perc = as_percent( prop, digits = 1 # To control formatting in ggplot + elsewhere ) ) gg_data ``` -------------------------------- ### Round percent vectors using digits attribute in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent Illustrates rounding a '' vector by setting the `digits` argument in `as_percent()`. This method controls the display and formatting of the percentage without altering the underlying numeric value, preserving flexibility for downstream calculations. ```r p2 <- as_percent(p, digits = 0) # Prints and formats to 0 decimal places print(p2) #> [1] "6%" as.character(p2) #> [1] "6%" # Underlying data has not been rounded! unclass(p2) #> [1] 0.055 #> attr(," .digits") #> [1] 0 ``` -------------------------------- ### Use floor, ceiling, trunc, and round with percent vectors in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent Applies various rounding functions (`floor`, `ceiling`, `trunc`, `round`) to '' vectors. This showcases how these functions operate on percent vectors, including specifying decimal places for `round()`. ```r percentages <- percent(seq(-0.1, 0.1, by = 0.05)) floor(percentages) #> [1] "-1%" "-1%" "0%" "0%" "0%" ceiling(percentages) #> [1] "0%" "0%" "0%" "1%" "1%" trunc(percentages) #> [1] "0%" "0%" "0%" "0%" "0%" round(percentages) #> [1] "0%" "0%" "0%" "0%" "0%" round(percentages, 1) #> [1] "-0.1%" "-0.1%" "0.0%" "0.1%" "0.1%" round(percentages, 2) #> [1] "-0.10%" "-0.05%" "0.00%" "0.05%" "0.10%" ``` -------------------------------- ### Check R Package Development Standards with devtools Source: https://public-health-scotland.github.io/phsmethods/index This R command uses the 'devtools' package to perform a comprehensive check on an R package, ensuring it adheres to development standards and best practices. It's crucial for maintaining package quality before submission. ```r devtools::check() ``` -------------------------------- ### Slice and Display Data with Percent Vectors in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent This snippet demonstrates how to slice the head of a data frame and display it, showing the 'species' column with associated counts and percentages. It utilizes the pipe operator for sequential data manipulation. ```R species |> slice_head(n = 5) ``` -------------------------------- ### Calculate File Size in R Source: https://public-health-scotland.github.io/phsmethods/reference/file_size The `file_size` function in R calculates the size of files within a specified directory that match an optional regular expression pattern. It returns a tibble with file names and sizes, handling various file extensions with specific prefixes and formatting sizes in appropriate byte multiples. If no files match or the directory is empty, it returns NULL. ```r file_size(filepath = getwd(), pattern = NULL) ``` ```r file_size(pattern = "\.xlsx$") ``` ```r library(magrittr) file_size() %>% dplyr::pull(size) %>% magrittr::extract(1) ``` -------------------------------- ### Calculate Statistical Summaries of Percent Vectors in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent This code calculates various statistical summaries (min, max, median, average, sum) for a 'perc' column within a data frame named 'species'. The results are stored in 'perc_summary' and then displayed. ```R perc_summary <- species | summarise( min = min(perc), max = max(perc), median = median(perc), avg = mean(perc), sum = sum(perc) ) perc_summary ``` -------------------------------- ### Calculate age relative to event date using age_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This code shows how to calculate age using `age_from_chi` where the reference date is dynamically set to the `event_date` column. This is useful for calculating age at the time of a specific event. ```r data %> mutate(age = age_from_chi(chi, ref_date = event_date)) ``` -------------------------------- ### Calculate age with fixed min/max age limits using age_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This code calculates age using `age_from_chi` with fixed `min_age` and `max_age` limits, and the reference date defaults to today. Ages outside this specified range will be set to NA. ```r data %> mutate(age = age_from_chi( chi, min_age = 60, max_age = 120 )) ``` -------------------------------- ### Create Age Groups in R Source: https://public-health-scotland.github.io/phsmethods/news/index Shows the `create_age_groups()` function, formerly `age_group()`, used for categorizing individuals into age groups. This function is part of the phsmethods package for demographic analysis. ```R create_age_groups(ages) ``` -------------------------------- ### Physically round percent vectors using round() in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent Shows how to use R's base `round()` function on a '' vector. This method modifies the underlying numeric value of the percentage, which can lead to accumulated errors if not handled carefully, unlike rounding via the `digits` attribute. ```r p3 <- round(p, digits = 0) p3 #> [1] "6%" # Underlying data has been rounded unclass(p3) #> [1] 0.06 #> attr(," .digits") #> [1] 2 ``` -------------------------------- ### Extract Financial Year in R Source: https://public-health-scotland.github.io/phsmethods/news/index Shows how to use the `extract_fin_year()` function from the phsmethods package to extract financial years from dates. The changelog notes improvements in speed and memory usage for this function, especially for smaller vectors. ```R extract_fin_year(dates) ``` -------------------------------- ### Calculate age with event date as ref_date and max_age limit using age_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This snippet calculates age using `age_from_chi` with the `event_date` as the reference date and also applies a `max_age` limit. Ages exceeding this limit will be capped or set to NA. ```r data %> mutate(age = age_from_chi(chi, ref_date = event_date, max_age = 18)) ``` -------------------------------- ### Format Postcodes in R Source: https://public-health-scotland.github.io/phsmethods/news/index Illustrates the usage of the `format_postcode()` function from the phsmethods package for formatting UK postcodes. It mentions the `quiet` parameter which can be used to skip checks and messages for faster processing when cleaning a vector of postcodes. ```R format_postcode(postcodes, quiet = TRUE) ``` -------------------------------- ### Assign a date to a quarter in R Source: https://public-health-scotland.github.io/phsmethods/reference/qtr The `qtr` functions in R take a date input and calculate the relevant quarter-related value, returning the year as part of the output. They handle different formats for displaying the quarter, such as 'long' (e.g., 'January to March 2018') and 'short' (e.g., 'Jan-Mar 2018'). These functions are useful for time-series analysis and reporting. ```R qtr(date, format = c("long", "short")) qtr_end(date, format = c("long", "short")) qtr_next(date, format = c("long", "short")) qtr_prev(date, format = c("long", "short")) ``` ```R x <- lubridate::dmy(c(26032012, 04052012, 23092012)) qtr(x) #> [1] "January to March 2012" "April to June 2012" "July to September 2012" qtr_end(x, format = "short") #> [1] "Mar 2012" "Jun 2012" "Sep 2012" qtr_next(x) #> [1] "April to June 2012" "July to September 2012" #> [3] "October to December 2012" qtr_prev(x, format = "short") #> [1] "Oct-Dec 2011" "Jan-Mar 2012" "Apr-Jun 2012" ``` -------------------------------- ### Create Age Groups Function in R Source: https://public-health-scotland.github.io/phsmethods/reference/create_age_groups The `create_age_groups` function in R takes a numeric vector of ages and assigns each age to a predefined age group. It allows customization of the age group range and size, and can return results as a character or factor vector. This function is useful for categorizing data into standard age brackets. ```R create_age_groups <- function(x, from = 0, to = 90, by = 5, as_factor = FALSE) { # Function implementation details would go here # For demonstration, a placeholder: if (as_factor) { return(factor(rep("0-4", length(x)))) } else { return(as.character(rep("0-4", length(x)))) } } ``` -------------------------------- ### Pad Leading Zero to Nine-Digit CHI Numbers in R Source: https://public-health-scotland.github.io/phsmethods/reference/chi_pad The `chi_pad` function in R adds a leading zero to nine-digit CHI numbers provided as character strings. It handles CHI numbers that may be missing this leading zero. Input values that are not nine-digit numeric strings are returned unchanged. The function ensures the output remains a character vector, as numeric types in R drop leading zeros. ```R chi_pad(c("101011237", "101201234")) #> [1] "0101011237" "0101201234" ``` -------------------------------- ### Format UK Postcodes in R Source: https://public-health-scotland.github.io/phsmethods/reference/format_postcode The format_postcode function takes a character string or vector of UK postcodes, standardizes their format (pc7 or pc8), capitalizes letters, and adds appropriate spacing. It handles variations in input spacing and capitalization. Invalid postcodes will result in NA values and warnings, which can be suppressed by setting quiet to TRUE. ```r format_postcode <- function(x, format = c("pc7", "pc8"), quiet = FALSE) { # Function implementation details... # Example usage: # format_postcode("G26QE") # format_postcode(c("KA89NB", "PA152TY"), format = "pc8") # library(dplyr) # df <- tibble(postcode = c("G429BA", "G207AL", "DD37JY", "DG98BS")) # df %>% # mutate(postcode = format_postcode(postcode)) invisible(NULL) # Placeholder for actual function logic } ``` -------------------------------- ### Create Polar Bar Chart with Percent Vector Aesthetics in ggplot2 in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent This code creates a polar bar chart (pie chart) visualizing the distribution of iris species proportions using percent vectors directly as aesthetics. It includes custom theming and labels for clarity. ```R gg_data | ggplot(aes(x = "", y = perc, fill = Species)) + geom_bar(stat = "identity", width = 1, color = "white") + coord_polar("y", start = 0) + theme_void() + geom_text(aes(label = perc), position = position_stack(vjust = 0.5)) + scale_fill_brewer(palette = "Set1") ``` -------------------------------- ### Create Bar Chart with Percent Vector Y-axis using ggplot2 in R Source: https://public-health-scotland.github.io/phsmethods/articles/percent This snippet generates a bar chart using 'ggplot2' where the y-axis represents proportions of iris species. It utilizes 'scale_y_continuous' with 'as_percent' to format the y-axis labels as percentages. ```R species_gg <- gg_data | ggplot(aes(Species)) + geom_col(aes(y = prop, fill = Species), width = 0.25) species_gg + scale_y_continuous(name = "Percentage", labels = as_percent) ``` -------------------------------- ### Extract age using default settings with age_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This snippet illustrates the basic usage of the `age_from_chi` function to extract a patient's age from a CHI number. By default, age is calculated relative to today's date. Ambiguous CHI numbers may result in NA for age. ```r data %> mutate(age = age_from_chi(chi)) ``` -------------------------------- ### Add Event Dates to Data Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This R code snippet adds an 'event_date' column to the dataset. This is often used in conjunction with DOB extraction from CHI numbers to provide temporal context for resolving date ambiguities. ```r data <- data %>% mutate(event_date = as.Date(c( "2015-01-01", "2014-01-01", "2013-01-01", "2012-01-01", "2011-01-01", "2010-01-01" ))) ``` -------------------------------- ### Extract DOB using event date as max_date with dob_from_chi Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This snippet demonstrates how to use the `dob_from_chi` function to extract a date of birth from a CHI number, using the `event_date` as the maximum possible date. It highlights potential issues with ambiguous CHI numbers resulting in NA for DOB. ```r data %> mutate(dob = dob_from_chi(chi, max_date = event_date)) ``` -------------------------------- ### Calculate Age Robustly in R Source: https://public-health-scotland.github.io/phsmethods/news/index Highlights the `age_calculate()` function, which has been improved for robustness in uncommon situations like leap years or when dates are provided as date-time objects. This function calculates age based on provided dates. ```R age_calculate(date_of_birth, reference_date) ``` -------------------------------- ### Translate Geography Codes to Area Names using R Source: https://public-health-scotland.github.io/phsmethods/reference/match_area The `match_area` function in R translates geography codes into their corresponding area names using the `area_lookup()` dataset. It handles various geography types and versions, returning NA for non-matching inputs. Case and spacing sensitivity are important for exact matches. ```r match_area("S20000010") #> [1] "Eaglesham" library(dplyr) df <- tibble(code = c("S02000656", "S02001042", "S08000020", "S12000013")) df %>% mutate(name = match_area(code)) #> # A tibble: 4 × 2 #> code name #> #> 1 S02000656 Govan and Linthouse #> 2 S02001042 Peebles North #> 3 S08000020 Grampian #> 4 S12000013 Na h-Eileanan Siar ``` -------------------------------- ### Extract Sex from CHI Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This R code snippet extracts sex information from CHI numbers using the `sex_from_chi` function. By default, sex is returned as an integer (1 for Male, 2 for Female). The `as_factor = TRUE` argument can be used to return sex as a factor with descriptive labels. ```r data_sex <- data %>% mutate(sex = sex_from_chi(chi, chi_check = FALSE)) data_sex ``` ```r data_sex <- data_sex %>% mutate(sex_factor = sex_from_chi(chi, as_factor = TRUE)) data_sex ``` -------------------------------- ### Visualize Sex Distribution Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This R code snippet uses ggplot2 to create a polar bar chart visualizing the distribution of sex (Male vs. Female) extracted from CHI numbers. It requires the `ggplot2` library and the `sex_factor` column generated previously. ```r library(ggplot2) data_sex %>% ggplot(aes(y = "", fill = sex_factor)) + geom_bar() + coord_polar() + labs(title = "Count of Male vs Female", x = "", y = "") + scale_fill_brewer("Sex (from CHI)", type = "qual") + theme_minimal() ``` -------------------------------- ### Extract Financial Year from Date in R Source: https://public-health-scotland.github.io/phsmethods/reference/extract_fin_year The `extract_fin_year` function in R takes a date object (Date, POSIXct, POSIXlt, or POSIXt) and returns the corresponding financial year in the PHS specified format 'YYYY/YY'. It handles date conversions and ensures the output matches the required format. ```R extract_fin_year <- function(date) { # Implementation details for extracting financial year # ... # Example usage: # x <- lubridate::dmy(c(21012017, 04042017, 17112017)) # extract_fin_year(x) # #> [1] "2016/17" "2017/18" "2017/18" } ``` -------------------------------- ### Extract Date of Birth from CHI Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This R code snippet extracts the Date of Birth (DOB) from CHI numbers using the `dob_from_chi` function. Due to the CHI format, DOB extraction can be ambiguous, returning NA for unclear dates. The `min_date` and `max_date` arguments can be used to provide context and resolve ambiguities. ```r data_dob <- data %>% mutate(dob = dob_from_chi(chi)) data_dob ``` ```r # Expect no one born after 2015-12-31 data %>% mutate(dob = dob_from_chi(chi, max_date = as.Date("2015-12-31"))) ``` ```r # Expect no one born before 1999-12-31 i.e. 16 years before our data started. data %>% mutate(dob = dob_from_chi( chi, max_date = as.Date("2015-12-31"), min_date = as.Date("2015-12-31") - lubridate::years(16) )) ``` -------------------------------- ### Calculate Age from CHI Number in R Source: https://public-health-scotland.github.io/phsmethods/news/index Demonstrates the `age_from_chi()` function for calculating age directly from a Community Health Index (CHI) number. The changelog mentions improvements to this function to handle edge cases and ensure test accuracy. ```R age_from_chi(chi_number) ``` -------------------------------- ### Extract Date of Birth (DoB) from CHI Number Source: https://public-health-scotland.github.io/phsmethods/reference/dob_from_chi The `dob_from_chi` function extracts the Date of Birth (DoB) from a given CHI number or a vector of CHI numbers. It handles potential ambiguities by returning NA. ```APIDOC ## POST /dob_from_chi ### Description Extracts the Date of Birth (DoB) from a CHI number or a vector of CHI numbers. Returns NA if the DoB is ambiguous. ### Method POST ### Endpoint /dob_from_chi ### Parameters #### Request Body - **chi_number** (character or vector of character) - Required - A CHI number or a vector of CHI numbers. - **min_date** (Date) - Optional - Minimum possible date for the DoB. Can be a single date or a vector of dates matching `chi_number` length. - **max_date** (Date) - Optional - Maximum possible date for the DoB. Can be a single date or a vector of dates matching `chi_number` length. - **chi_check** (logical) - Optional - If TRUE (default), checks the validity of the CHI numbers. Set to FALSE to skip checking for faster processing if CHI numbers are pre-validated. ### Request Example ```json { "chi_number": "0101336489", "min_date": null, "max_date": null, "chi_check": true } ``` ### Response #### Success Response (200) - **dob** (Date or vector of Date) - The extracted Date of Birth(s) corresponding to the input CHI number(s). #### Response Example ```json { "dob": "1933-01-01" } ``` ``` -------------------------------- ### Handle Invalid CHI Numbers by Setting to NA or Filtering Source: https://public-health-scotland.github.io/phsmethods/articles/chi-operations This snippet shows two methods for handling invalid CHI numbers in a data frame: converting them to NA using if_else() and chi_check(), or filtering out rows with invalid CHIs using filter() and chi_check(). Both methods rely on the chi_check() function to identify invalid entries. ```r fixed_data %>% mutate(chi = if_else(chi_check(chi) != "Valid CHI", NA_character_, chi)) #> # A tibble: 8 × 1 #> chi #> #> 1 0211165794 #> 2 NA #> 3 0402070763 #> 4 NA #> 5 NA #> 6 NA #> 7 NA #> 8 NA fixed_data %>% filter(chi_check(chi) == "Valid CHI") #> # A tibble: 2 × 1 #> chi #> #> 1 0211165794 #> 2 0402070763 ``` -------------------------------- ### Extract Age from CHI Number in R Source: https://public-health-scotland.github.io/phsmethods/reference/age_from_chi The `age_from_chi` function takes a CHI number or a vector of CHI numbers and returns the age as implied by the CHI number(s). It uses `dob_from_chi()` and returns NA if the Date of Birth is ambiguous. Optional arguments allow specifying a reference date, minimum/maximum age bounds, and whether to perform CHI number validity checks. ```r age_from_chi( chi_number, ref_date = NULL, min_age = 0L, max_age = NULL, chi_check = TRUE ) ``` ```r age_from_chi("0101336489") #> [1] 93 library(tibble) library(dplyr) data <- tibble( chi = c( "0101336489", "0101405073", "0101625707" ), dis_date = as.Date(c( "1950-01-01", "2000-01-01", "2020-01-01" )) ) data %>% mutate(chi_age = age_from_chi(chi)) #> # A tibble: 3 × 3 #> chi dis_date chi_age #> #> 1 0101336489 1950-01-01 93 #> 2 0101405073 2000-01-01 86 #> 3 0101625707 2020-01-01 64 data %>% mutate(chi_age = age_from_chi(chi, min_age = 18, max_age = 65)) #> ! 2 CHI numbers produced ambiguous dates and will be given "NA" for their Dates #> of Birth. #> ✔ Try different values for `min_age` and/or `max_age`. #> # A tibble: 3 × 3 #> chi dis_date chi_age #> #> 1 0101336489 1950-01-01 NA #> 2 0101405073 2000-01-01 NA #> 3 0101625707 2020-01-01 64 data %>% mutate(chi_age = age_from_chi(chi, ref_date = dis_date )) #> # A tibble: 3 × 3 #> chi dis_date chi_age #> #> 1 0101336489 1950-01-01 17 #> 2 0101405073 2000-01-01 60 #> 3 0101625707 2020-01-01 58 ``` -------------------------------- ### Extract Sex from CHI Number (R) Source: https://public-health-scotland.github.io/phsmethods/reference/sex_from_chi Extracts sex information from a CHI number or a vector of CHI numbers. It can return integers, custom values, or factors. The function includes an option to validate the CHI number. ```R sex_from_chi( chi_number, male_value = 1L, female_value = 2L, as_factor = FALSE, chi_check = TRUE ) ``` ```R sex_from_chi("0101011237") #> [1] 1 sex_from_chi(c("0101011237", "0101336489", NA)) #> [1] 1 2 NA sex_from_chi( c("0101011237", "0101336489", NA), male_value = "M", female_value = "F" ) #> Using custom values: Male = "M", Female = "F" #> The return variable will be . #> [1] "M" "F" NA sex_from_chi(c("0101011237", "0101336489", NA), as_factor = TRUE) #> [1] Male Female #> Levels: Male Female library(dplyr) df <- tibble(chi = c("0101011237", "0101336489", NA)) df %>% mutate(chi_sex = sex_from_chi(chi)) #> # A tibble: 3 × 2 #> chi chi_sex #> #> 1 0101011237 1 #> 2 0101336489 2 #> 3 NA NA ```