### Example of grouping the mtcars dataset Source: https://dplyr.tidyverse.org/reference/group_by.html A practical example showing how to group the built-in mtcars dataset by the 'cyl' variable. ```R by_cyl <- mtcars |> group_by(cyl) # Display the grouped tibble by_cyl ``` -------------------------------- ### Dplyr: Example of basic join_by with equality Source: https://dplyr.tidyverse.org/reference/join_by.html This example demonstrates a basic join using `join_by()` to match rows based on an exact equality condition between columns from two tibbles. It uses `left_join()` to combine the `sales` and `promos` tibbles where `id` matches and `sale_date` equals `promo_date`. ```r sales <- tibble( id = c(1L, 1L, 1L, 2L, 2L), sale_date = as.Date(c("2018-12-31", "2019-01-02", "2019-01-05", "2019-01-04", "2019-01-01")) ) promos <- tibble( id = c(1L, 1L, 2L), promo_date = as.Date(c("2019-01-01", "2019-01-05", "2019-01-02")) ) # Match `id` to `id`, and `sale_date` to `promo_date` by <- join_by(id, sale_date == promo_date) left_join(sales, promos, by) ``` -------------------------------- ### Example Output of Band Member Data (R) Source: https://dplyr.tidyverse.org/reference/band_members.html Shows the expected output when displaying the `band_members`, `band_instruments`, and `band_instruments2` tibbles. This illustrates the structure and content of these sample datasets. ```R band_members #> # A tibble: 3 × 2 #> name band #> #> 1 Mick Stones #> 2 John Beatles #> 3 Paul Beatles band_instruments #> # A tibble: 3 × 2 #> name plays #> #> 1 John guitar #> 2 Paul bass #> 3 Keith guitar band_instruments2 #> # A tibble: 3 × 2 #> artist plays #> #> 1 John guitar #> 2 Paul bass #> 3 Keith guitar ``` -------------------------------- ### dplyr Improvements: `slice_sample()` Example for Shuffling Source: https://dplyr.tidyverse.org/news/index.html A new example has been added for `slice_sample()` in dplyr, demonstrating how to use it to shuffle rows. This provides a practical use case for the function. ```r New `slice_sample()` example showing how to use it to shuffle rows (#7707, @Hzanib). ``` -------------------------------- ### Inspect Starwars Dataset using dplyr Source: https://dplyr.tidyverse.org/reference/glimpse.html This example uses the glimpse() function from the dplyr package to provide a concise summary of the 'starwars' dataset. It shows the number of rows and columns, along with the data type and first few values for each column. ```r glimpse(starwars) ``` -------------------------------- ### Select Columns Starting with 'Sepal' using `pick()` in R Source: https://dplyr.tidyverse.org/reference/arrange.html This code snippet demonstrates how to select columns from the 'iris' dataset that start with the string 'Sepal' using the `pick()` function in R. It utilizes the `dplyr` package for data manipulation. The output is the 'iris' dataset sorted by the selected 'Sepal' columns. ```r library(dplyr) iris |> arrange(pick(starts_with("Sepal"))) ``` -------------------------------- ### Nest a tibble using group_nest Source: https://dplyr.tidyverse.org/reference/group_nest.html Demonstrates how to use group_nest to organize data into a list column. It shows examples for both pre-grouped data frames and applying grouping specifications to ungrouped data. ```R # Use case 1: a grouped data frame iris |> group_by(Species) |> group_nest() # Altered grouped data before nesting iris |> group_by(Species) |> filter(Sepal.Length > mean(Sepal.Length)) |> group_nest() # Use case 2: using group_nest() on an ungrouped data frame starwars |> group_nest(species, homeworld) ``` -------------------------------- ### dplyr Improvements: `across()` Example with `everything()` Source: https://dplyr.tidyverse.org/news/index.html Examples for the `across()` function in dplyr have been updated to include a demonstration of using `everything()`. This showcases a more comprehensive way to apply functions across all columns. ```r Updated `across()` examples to include an example using `everything()` (#7621, @JBrandenburg02). ``` -------------------------------- ### Transform column names with rename_with Source: https://dplyr.tidyverse.org/reference/rename.html Shows how to apply functions to column names using rename_with(). Examples include converting to uppercase, targeting specific columns, and using regex to format names. ```R rename_with(iris, toupper) rename_with(iris, toupper, starts_with("Petal")) rename_with(iris, ~ tolower(gsub(".", "_", .x, fixed = TRUE))) ``` -------------------------------- ### Custom Unpacking with reframe and glue Source: https://dplyr.tidyverse.org/reference/across.html This example demonstrates using `reframe` with `across` and `quantile_df`, but customizes the output column names using a glue specification for `.unpack`. This allows for more control over how the new columns are named, for instance, using a dot separator. ```r iris |> reframe(across(starts_with("Sepal"), quantile_df, .unpack = "{outer}.{inner}")) ``` -------------------------------- ### Count and tally observations in R Source: https://dplyr.tidyverse.org/reference/count.html Demonstrates how to use count() and tally() to aggregate data. The examples show basic frequency counting, sorting results, grouping by multiple variables, and using weighted counts with the wt argument. ```R # Basic counting of species starwars |> count(species) # Counting with sorting starwars |> count(species, sort = TRUE) # Grouping by multiple variables starwars |> count(sex, gender, sort = TRUE) # Counting with transformations starwars |> count(birth_decade = round(birth_year, -1)) # Weighted counts df <- tribble( ~name, ~gender, ~runs, "Max", "male", 10, "Sandra", "female", 1, "Susan", "female", 4 ) df |> count(gender, wt = runs) ``` -------------------------------- ### Select columns with dplyr Source: https://dplyr.tidyverse.org/index.html Selects specific columns from a dataframe. This example keeps the 'name' column and any columns ending with 'color'. ```R library(dplyr) starwars |> select(name, ends_with("color")) ``` -------------------------------- ### Dplyr: Join_by with inequality condition Source: https://dplyr.tidyverse.org/reference/join_by.html This example shows how to use `join_by()` with an inequality condition to find promotions that occurred before a sale. It performs a `left_join()` between `sales` and `promos` where `id` matches and `sale_date` is greater than or equal to `promo_date`. ```r sales <- tibble( id = c(1L, 1L, 1L, 2L, 2L), sale_date = as.Date(c("2018-12-31", "2019-01-02", "2019-01-05", "2019-01-04", "2019-01-01")) ) promos <- tibble( id = c(1L, 1L, 2L), promo_date = as.Date(c("2019-01-01", "2019-01-05", "2019-01-02")) ) # For each `sale_date` within a particular `id`, # find all `promo_date`s that occurred before that particular sale by <- join_by(id, sale_date >= promo_date) left_join(sales, promos, by) ``` -------------------------------- ### Programmatically create a tibble column name using glue syntax Source: https://dplyr.tidyverse.org/articles/programming.html This example demonstrates how to create a tibble with a column name that is determined by a variable. It uses glue syntax `"{name}" := value` to inject the value of the `name` variable as the column name. ```r name <- "susan" tibble("{name}" := 2) #> # A tibble: 1 × 1 #> susan #> #> 1 2 ``` -------------------------------- ### Join by Segment Start within Reference Range using dplyr Source: https://dplyr.tidyverse.org/reference/join_by.html This example shows how to join `segments` and `reference` data frames where the `start` of a segment falls within the `[start, end]` range of a reference. It utilizes `join_by` with the `between` function to define the join condition based on the chromosome and the start position relative to the reference range. This is common in genomic data analysis. ```r by <- join_by(chromosome, between(start, start, end)) full_join(segments, reference, by) ``` -------------------------------- ### Select columns using dplyr Source: https://dplyr.tidyverse.org/reference/select.html Demonstrates the basic usage of the select function and the initialization of the tidyverse environment for data manipulation. ```R library(tidyverse) # Basic usage of select # select(.data, ...) # Example: Selecting columns by name or range # df %>% select(column_a, column_b:column_f) # Example: Selecting by type # df %>% select(where(is.numeric)) ``` -------------------------------- ### Define IDs for Banned Shoes and False Starts Source: https://dplyr.tidyverse.org/articles/recoding-replacing.html This snippet defines two vectors, `id_banned_shoes` and `id_false_start`, which store the IDs of racers who used banned shoes or had a false start, respectively. These vectors are used in subsequent examples to demonstrate conditional replacements. ```r id_banned_shoes <- c(2, 10, 15, 32, 65) id_false_start <- c(1, 2, 5, 20, 55, 74, 91) ``` -------------------------------- ### Migrating Scoped Renaming to rename_with Source: https://dplyr.tidyverse.org/reference/select_all.html Demonstrates replacing legacy functions like rename_if and rename_at with the modern rename_with function. These examples show how to apply transformations like toupper to columns based on conditional logic or specific selection ranges. ```R is_whole <- function(x) all(floor(x) == x) # Legacy: rename_if mtcars |> rename_if(is_whole, toupper) # Modern: rename_with mtcars |> rename_with(toupper, where(is_whole)) # Legacy: rename_at mtcars |> rename_at(vars(mpg:hp), toupper) # Modern: rename_with mtcars |> rename_with(toupper, mpg:hp) # Legacy: select_all mtcars |> select_all(toupper) ``` -------------------------------- ### Join by Segment Start within Reference Range (Reversed Order) using dplyr Source: https://dplyr.tidyverse.org/reference/join_by.html This snippet illustrates performing the same join as the previous example but with the order of data frames reversed (`reference` as `x` and `segments` as `y`). It explicitly uses `x$` and `y$` to clarify which data frame's columns are being referenced in the `join_by` condition, ensuring the `start` of the segment falls within the `start` and `end` of the reference. ```r by <- join_by(chromosome, between(y$start, x$start, x$end)) full_join(reference, segments, by) ``` -------------------------------- ### Generate Combinations and Simulate with expand.grid() Source: https://dplyr.tidyverse.org/articles/rowwise.html Generates all combinations of 'mean' and 'sd' parameters using expand.grid() and then performs simulations using rnorm() for each combination. This demonstrates how to simulate data for every possible pairing of input parameters. ```r df <- expand.grid(mean = c(-1, 0, 1), sd = c(1, 10, 100)) df |> rowwise() |> mutate(data = list(rnorm(10, mean, sd))) ``` -------------------------------- ### Join by Segment Completely Within Reference using dplyr Source: https://dplyr.tidyverse.org/reference/join_by.html This example demonstrates finding segments that are entirely contained within a reference range. It uses `join_by` with the `within` function, specifying that the segment's start and end must fall within the reference's start and end. An `inner_join` is used to return only the matching segments and references. ```r by <- join_by(chromosome, within(x$start, x$end, y$start, y$end)) inner_join(segments, reference, by) ``` -------------------------------- ### Select a range of variables with dplyr::select() Source: https://dplyr.tidyverse.org/reference/select.html This example shows how to use the colon operator (:) within dplyr's select() function to select a contiguous range of variables from a data frame. The selection includes the starting and ending variable names specified. This is a concise way to select multiple adjacent columns. ```r library(dplyr) starwars |> select(name:mass) ``` -------------------------------- ### Apply transformations using selection helpers in R Source: https://dplyr.tidyverse.org/reference/mutate_all.html Demonstrates applying a log transformation to columns matching a pattern. It compares the legacy mutate_at approach with the modern across approach using the matches helper. ```R iris |> mutate_at(vars(matches("Sepal")), log) iris |> mutate(across(matches("Sepal"), log)) ``` -------------------------------- ### Data Preparation and Basic Mutation Source: https://dplyr.tidyverse.org/articles/dplyr.html Initializes a subset of the starwars dataset and demonstrates how mutate() treats inputs as column vectors. It shows that passing strings or numbers results in new columns created via vector recycling. ```R df <- starwars |> select(name, height, mass) mutate(df, "height", 2) ``` -------------------------------- ### Demonstrating subsetting logic with loops Source: https://dplyr.tidyverse.org/articles/rowwise.html A conceptual demonstration of how grouped and row-wise operations differ using standard R for-loops. ```R # grouped out1 <- integer(2) for (i in 1:2) { out1[[i]] <- length(df$y[i]) } # rowwise out2 <- integer(2) for (i in 1:2) { out2[[i]] <- length(df$y[[i]]) } ``` -------------------------------- ### Get first row of each group using do() (superseded) Source: https://dplyr.tidyverse.org/articles/rowwise.html This R code snippet demonstrates how to use the deprecated `do()` function from the dplyr package to get the first row of each group in the 'mtcars' dataset. It is now superseded by `pick()` and `reframe()`. ```r mtcars |> group_by(cyl) | do(head(., 1)) ``` -------------------------------- ### Get first row of each group using pick() and reframe() Source: https://dplyr.tidyverse.org/articles/rowwise.html This R code snippet shows the modern approach to getting the first row of each group in the 'mtcars' dataset using `pick()` and `reframe()`, which supersedes the older `do()` function. ```r mtcars |> group_by(cyl) | reframe(head(pick(everything()), 1)) ``` -------------------------------- ### Internal implementation of pick() Source: https://dplyr.tidyverse.org/reference/pick.html Shows the underlying logic used to replicate pick() behavior using vctrs and tibble packages for empty selections. ```R size <- vctrs::vec_size_common(..., .absent = 1L) out <- vctrs::vec_recycle_common(..., .size = size) tibble::new_tibble(out, nrow = size) ``` -------------------------------- ### Programming with dynamic inputs in when_any and when_all Source: https://dplyr.tidyverse.org/reference/when-any-all.html Shows how to handle variable-length input lists using the size argument to ensure stable output. This is useful for programmatic generation of conditions where the number of inputs is unknown. ```R size <- length(x) # Two inputs inputs <- list(x, y) when_all(!!!inputs, size = size) # One input inputs <- list(x) when_all(!!!inputs, size = size) # Zero inputs inputs <- list() when_all(!!!inputs, size = size) # Consistent behavior with base R any() when_any(size = 1) all() when_all(size = 1) ``` -------------------------------- ### GET /is.src Source: https://dplyr.tidyverse.org/reference/src.html Tests whether an object is a valid src instance. ```APIDOC ## GET /is.src ### Description Tests if the provided object is of the "src" class. ### Method GET ### Endpoint /is.src ### Parameters #### Query Parameters - **x** (object) - Required - The object to test for "src"-ness. ### Request Example { "x": "object_to_test" } ### Response #### Success Response (200) - **result** (boolean) - Returns true if the object is an instance of src, false otherwise. #### Response Example { "result": true } ``` -------------------------------- ### Select columns with helpers Source: https://dplyr.tidyverse.org/news/index.html Demonstrates the use of select helpers to manipulate column selection, including negating matches to return all columns. ```R library(dplyr) # Negating a match returns all columns except those containing 'x' select(mtcars, -contains("x")) ``` -------------------------------- ### Filter Last Row using dplyr row_number() and n() in R Source: https://dplyr.tidyverse.org/reference/slice.html This code snippet filters the last row of the 'mtcars' dataset. It uses `row_number()` to get the current row number and `n()` to get the total number of rows, comparing them to identify the last row. Requires the dplyr package. ```r filter(mtcars, row_number() == n()) ``` -------------------------------- ### Arrange data rows with dplyr Source: https://dplyr.tidyverse.org/index.html Sorts rows in a dataframe. This example arranges the dataset by mass in descending order. ```R library(dplyr) starwars |> arrange(desc(mass)) ``` -------------------------------- ### Initialize Lahman Batting Data for Window Functions Source: https://dplyr.tidyverse.org/articles/window-functions.html Prepares the Lahman batting dataset by converting it to a tibble, selecting relevant columns, and grouping by playerID to enable window function operations. ```R library(Lahman) batting <- Lahman::Batting |> as_tibble() |> select(playerID, yearID, teamID, G, AB:H) |> arrange(playerID, yearID, teamID) |> semi_join(Lahman::AwardsPlayers, by = "playerID") players <- batting |> group_by(playerID) ``` -------------------------------- ### Filter rows with dplyr Source: https://dplyr.tidyverse.org/index.html Filters rows in a dataframe based on specific criteria. This example extracts all rows where the species is 'Droid'. ```R library(dplyr) starwars |> filter(species == "Droid") ``` -------------------------------- ### GET src_tbls Source: https://dplyr.tidyverse.org/reference/src_tbls.html Retrieves a list of tables available within a given data source object. ```APIDOC ## GET src_tbls ### Description This is a generic method used to list all tables provided by a specific data source. It is intended to be implemented by individual source types. ### Method GET ### Endpoint src_tbls(x, ...) ### Parameters #### Path Parameters - **x** (data src) - Required - The data source object from which to retrieve table names. #### Query Parameters - **...** (dots) - Optional - Additional arguments passed to individual source-specific methods. ### Request Example src_tbls(my_db_source) ### Response #### Success Response (200) - **tables** (array of strings) - A list of table names available in the source. #### Response Example ["table1", "table2", "users"] ``` -------------------------------- ### Create Factor Tiers with case_when Source: https://dplyr.tidyverse.org/articles/recoding-replacing.html Initializes a dataset of race times and categorizes them into factor levels A through D and unknown using case_when. ```R id_with_malfunction <- c(1, 5, 20, 50) tiers <- racers |> mutate( tier = case_when( time < 23 ~ "A", time < 27 ~ "B", time < 30 ~ "C", time < 33 ~ "D", .default = "unknown" ) |> factor(levels = c("A", "B", "C", "D", "unknown")) ) ``` -------------------------------- ### Group and summarise data with dplyr Source: https://dplyr.tidyverse.org/index.html Aggregates data by groups and calculates summary statistics. This example groups by species and calculates the mean mass for groups with more than one member. ```R library(dplyr) starwars |> group_by(species) |> summarise( n = n(), mass = mean(mass, na.rm = TRUE) ) |> filter( n > 1, mass > 50 ) ``` -------------------------------- ### Get Grouping Variable Names with dplyr Source: https://dplyr.tidyverse.org/articles/grouping.html Extracts only the names of the variables used for grouping. Provides a quick way to check the current grouping structure. ```r by_species |> group_vars() #> [1] "species" by_sex_gender |> group_vars() #> [1] "sex" "gender" ``` -------------------------------- ### Apply transformations using external vectors in R Source: https://dplyr.tidyverse.org/reference/across.html Shows how to use an external character vector to specify columns for transformation using the all_of() helper. This is useful for dynamic column selection based on programmatically generated lists. ```R library(dplyr) cols <- c("Sepal.Length", "Petal.Width") iris |> mutate(across(all_of(cols), round)) ``` -------------------------------- ### Get Group Indices with dplyr Source: https://dplyr.tidyverse.org/articles/grouping.html Identifies which group each row belongs to. Returns a vector of integers representing the group index for each row in the data frame. ```r by_species |> group_indices() #> [1] 11 6 6 11 11 11 11 6 11 11 11 11 34 11 24 12 11 38 36 11 11 6 #> [23] 31 11 11 18 11 11 8 26 11 21 11 11 10 10 10 11 30 7 11 11 37 32 #> [45] 32 1 33 35 29 11 3 20 37 27 13 23 16 4 38 38 11 9 17 17 11 11 #> [67] 11 11 5 2 15 15 11 6 25 19 28 14 34 11 38 22 11 11 11 6 11 ``` -------------------------------- ### Count combinations of columns containing 'color' using pick() in R Source: https://dplyr.tidyverse.org/articles/colwise.html Demonstrates how to count all combinations of variables that match a given pattern using pick() and count() in R. This facilitates frequency analysis of categorical data. ```r starwars |> count(pick(contains("color")), sort = TRUE) ``` -------------------------------- ### Summarise Data by Group with dplyr Source: https://dplyr.tidyverse.org/articles/grouping.html Computes summary statistics for each group in a grouped data frame. The output starts from group keys and adds summary variables. ```r by_species |> summarise( n = n(), height = mean(height, na.rm = TRUE) ) #> # A tibble: 38 × 3 #> species n height #> #> 1 Aleena 1 79 #> 2 Besalisk 1 198 #> 3 Cerean 1 198 #> 4 Chagrian 1 196 #> # ℹ 34 more rows ``` -------------------------------- ### Select columns with pick() in R Source: https://dplyr.tidyverse.org/reference/pick.html Demonstrates how to use pick() to select specific columns within a mutate() call and how to use it as a bridge for custom grouping functions. ```R library(dplyr) df <- tibble( x = c(3, 2, 2, 2, 1), y = c(0, 2, 1, 1, 4), z1 = c("a", "a", "a", "b", "a"), z2 = c("c", "d", "d", "a", "c") ) # Select columns x and y df |> mutate(cols = pick(x, y)) # Compute rank based on multiple columns df |> mutate(rank = dense_rank(pick(x, y))) # Create a wrapper for grouping my_group_by <- function(data, cols) { group_by(data, pick({{ cols }})) } df |> my_group_by(c(x, starts_with("z"))) ``` -------------------------------- ### Handle Unmatched Values in case_when (R) Source: https://dplyr.tidyverse.org/reference/case-and-replace-when.html Demonstrates how `case_when` throws an error when values are not matched by any condition. It shows the correct way to handle unmatched values by adding a specific condition for them. ```r try(case_when( x < 10 ~ "ten", x < 20 ~ "twenty", x < 30 ~ "thirty", x < 40 ~ "forty", x < 50 ~ "fifty", .unmatched = "error" )) case_when( x < 10 ~ "ten", x < 20 ~ "twenty", x < 30 ~ "thirty", x < 40 ~ "forty", x <= 50 ~ "fifty", .unmatched = "error" ) ``` -------------------------------- ### case_match() - Deprecated Function Source: https://dplyr.tidyverse.org/reference/case_match.html This section details the deprecated case_match() function, explaining its purpose, arguments, and providing examples. It highlights that case_match() is superseded by recode_values() and replace_values(). ```APIDOC ## case_match() ### Description A general vectorised `switch()` that allows vectorising multiple `switch()` statements. Each case is evaluated sequentially and the first match for each element determines the corresponding value in the output vector. If no cases match, the `.default` is used. This function is deprecated and users should use `recode_values()` and `replace_values()` instead. ### Method N/A (R function) ### Endpoint N/A (R function) ### Arguments #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **.x** (vector) - A vector to match against. * **...** (`dynamic-dots`) - A sequence of two-sided formulas: `old_values ~ new_value`. The LHS must evaluate to the same type of vector as `.x`. The RHS inputs will be coerced to their common type and recycled to the size of `.x`. If a value is repeated in the LHS, the first match is used. * **.default** (any) - The value used when values in `.x` aren't matched by any of the LHS inputs. If `NULL`, a missing value will be used. Recycled to the size of `.x`. * **.ptype** (prototype) - An optional prototype declaring the desired output type. If not supplied, the output type will be taken from the common type of all RHS inputs and `.default`. ### Request Example ```R x <- c("a", "b", "a", "d", "b", NA, "c", "e") case_match( x, "a" ~ 1, "b" ~ 2, "c" ~ 3, "d" ~ 4 ) y <- as.integer(c(1, 2, 1, 3, 1, NA, 2, 4)) case_match( y, c(1, 3) ~ "odd", c(2, 4) ~ "even", .default = "missing" ) case_match(y, NA ~ 0, .default = y) ``` ### Response #### Success Response (200) * **vector** (vector) - A vector with the same size as `.x` and the same type as the common type of the RHS inputs and `.default` (if not overridden by `.ptype`). #### Response Example ```R # For x: # [1] 1 2 1 4 2 NA 3 NA # For y (first example): # [1] "odd" "even" "odd" "odd" "odd" "missing" "even" "even" # For y (second example): # [1] 1 2 1 3 1 0 2 4 ``` ``` -------------------------------- ### Implement Conditional Logic with NULL Handling in R Source: https://dplyr.tidyverse.org/reference/case-and-replace-when.html Demonstrates how case_when ignores NULL inputs, allowing for dynamic conditional logic by toggling parameters within the function definition. ```R case_character_type <- function(height, mass, species, robots = TRUE) { case_when( height > 200 | mass > 200 ~ "large", if (robots) species == "Droid" ~ "robot", .default = "other" ) } starwars |> mutate(type = case_character_type(height, mass, species, robots = FALSE)) |> pull(type) ``` -------------------------------- ### Mutate and calculate new columns with dplyr Source: https://dplyr.tidyverse.org/index.html Creates new variables or modifies existing ones. This example calculates Body Mass Index (BMI) based on mass and height columns. ```R library(dplyr) starwars |> mutate(name, bmi = mass / ((height / 100)^2)) |> select(name:mass, bmi) ``` -------------------------------- ### Integrate dynamic variables with Shiny inputs Source: https://dplyr.tidyverse.org/articles/programming.html Illustrates how to use Shiny input values to dynamically filter data frames by leveraging the .data pronoun within a reactive context. ```R library(shiny) ui <- fluidPage( selectInput("var", "Variable", choices = names(diamonds)), tableOutput("output") ) server <- function(input, output, session) { data <- reactive(filter(diamonds, .data[[input$var]] > 0)) output$output <- renderTable(head(data())) } ``` -------------------------------- ### Conditional replacement with replace_when Source: https://dplyr.tidyverse.org/articles/recoding-replacing.html Shows how to use replace_when for type-stable partial updates of existing columns compared to if_else. ```R x <- c(1, 6, 3, 8) new <- 10 # Type stable partial update x <- x |> replace_when(x > 5 ~ new) ``` -------------------------------- ### Migrating Scoped Verbs to across() Source: https://dplyr.tidyverse.org/articles/in-packages.html Examples of replacing deprecated scoped verbs (mutate_all, mutate_at, mutate_if) with the modern across() function for consistent data manipulation. ```R # Replacing mutate_all/each starwars |> mutate(across(everything(), as.character)) # Replacing mutate_at starwars |> mutate(across(c(height, mass), as.character)) # Replacing mutate_if starwars |> mutate(across(where(is.factor), as.character)) ``` -------------------------------- ### Filter data using logical criteria Source: https://dplyr.tidyverse.org/reference/filter.html Examples of filtering a dataset based on single and multiple logical conditions. It demonstrates the use of equality operators and logical operators like AND (&) and OR (|). ```R # Filtering for one criterion filter(starwars, species == "Human") # Filtering for multiple criteria within a single logical expression filter(starwars, hair_color == "none" & eye_color == "black") filter(starwars, hair_color == "none" | eye_color == "black") ``` -------------------------------- ### Perform grouped and ungrouped mutations Source: https://dplyr.tidyverse.org/reference/mutate.html Examples demonstrating how mutate() behaves differently when applied to ungrouped data versus data grouped by a specific variable like species. ```R # Ungrouped mutate starwars |> select(name, mass, species) |> mutate(mass_norm = mass / mean(mass, na.rm = TRUE)) # Grouped mutate starwars |> select(name, mass, species) |> group_by(species) |> mutate(mass_norm = mass / mean(mass, na.rm = TRUE)) ``` -------------------------------- ### Partial data replacement using replace_values Source: https://dplyr.tidyverse.org/articles/recoding-replacing.html Demonstrates how to use replace_values to collapse specific values into categories. It shows both formula-based mapping and the use of lookup tables for cleaner code. ```R library(dplyr) library(tibble) schools <- tibble(name = c("UNC", "Chapel Hill", NA, "Duke", "Duke University", "UNC", "NC State", "ECU")) # Using formula mapping schools |> mutate( name = name |> replace_values( c("UNC", "Chapel Hill") ~ "UNC Chapel Hill", c("Duke", "Duke University") ~ "Duke" ) ) # Using lookup tables lookup <- tribble( ~from, ~to, c("UNC", "Chapel Hill"), "UNC Chapel Hill", c("Duke", "Duke University"), "Duke" ) schools |> mutate(name = replace_values(name, from = lookup$from, to = lookup$to)) ``` -------------------------------- ### R: Deprecated Group Indices Function Source: https://dplyr.tidyverse.org/news/index.html Notes the deprecation of `group_indices()` when called without arguments. Use `cur_group_id()` to get the current group identifier within a dplyr operation. ```r # Deprecated: group_indices(df) # Recommended: # Inside a dplyr verb: cur_group_id() ``` -------------------------------- ### Apply conditional transformations to numeric columns in R Source: https://dplyr.tidyverse.org/reference/mutate_all.html Demonstrates scaling numeric columns within a dataset. It shows both the legacy mutate_if approach and the modern across syntax for applying functions conditionally. ```R starwars |> mutate_if(is.numeric, scale2, na.rm = TRUE) starwars |> mutate(across(where(is.numeric), ~ scale2(.x, na.rm = TRUE))) ``` -------------------------------- ### dplyr 1.1.3: Deprecation Messages for `*_each()` Functions Source: https://dplyr.tidyverse.org/news/index.html In dplyr 1.1.3, `mutate_each()` and `summarise_each()` now provide correct deprecation messages. This guides users towards the modern alternatives for these functions. ```r `mutate_each()` and `summarise_each()` now throw correct deprecation messages (#6869). ``` -------------------------------- ### Sample rows from a data frame using R Source: https://dplyr.tidyverse.org/reference/sample_n.html Demonstrates how to sample a specific number of rows or a fraction of rows from a tibble. It compares the legacy functions sample_n() and sample_frac() with the recommended slice_sample() function. ```R library(dplyr) df <- tibble(x = 1:5, w = c(0.1, 0.1, 0.1, 2, 2)) # Sampling by count slice_sample(df, n = 3) slice_sample(df, n = 10, replace = TRUE) slice_sample(df, n = 3, weight_by = w) # Sampling by fraction slice_sample(df, prop = 0.25) slice_sample(df, prop = 2, replace = TRUE) ``` -------------------------------- ### Reorganize Summaries with relocate() Source: https://dplyr.tidyverse.org/articles/colwise.html Applies multiple summary functions using across() with a custom naming scheme and then reorganizes the resulting columns using relocate() to group columns starting with 'min'. ```r starwars |> summarise(across(where(is.numeric), min_max, .names = "{.fn}.{.col}")) | relocate(starts_with("min")) ``` -------------------------------- ### R: Case When vs. If Else Statements Source: https://dplyr.tidyverse.org/news/index.html Demonstrates the recommended way to handle complex conditional logic in R using if-else statements instead of the deprecated style of case_when(). This approach improves clarity and avoids potential silent bugs. ```r # Scalars! code <- 1L flavor <- "vanilla" # Improper usage: case_when( code == 1L && flavor == "chocolate" ~ x, code == 1L && flavor == "vanilla" ~ y, code == 2L && flavor == "vanilla" ~ z, .default = default ) # Recommended: if (code == 1L && flavor == "chocolate") { x } else if (code == 1L && flavor == "vanilla") { y } else if (code == 2L && flavor == "vanilla") { z } else { default } ``` -------------------------------- ### Summarize user-supplied variables with across and pick Source: https://dplyr.tidyverse.org/articles/programming.html Demonstrates how to create reusable functions that accept data-variables as arguments. It utilizes across() for column-wise operations and pick() for flexible grouping. ```R my_summarise <- function(data, summary_vars) { data |> summarise(across({{ summary_vars }}, ~ mean(., na.rm = TRUE))) } starwars |> group_by(species) |> my_summarise(c(mass, height)) ``` ```R my_summarise <- function(data, group_var, summarise_var) { data |> group_by(pick({{ group_var }})) |> summarise(across({{ summarise_var }}, mean)) } ``` ```R my_summarise <- function(data, group_var, summarise_var) { data |> group_by(pick({{ group_var }})) |> summarise(across({{ summarise_var }}, mean, .names = "mean_{.col}")) } ``` -------------------------------- ### Select minimum values with dplyr slice_min Source: https://dplyr.tidyverse.org/reference/slice.html Demonstrates selecting rows with the minimum value of a column. Includes examples of handling ties and using multiple variables to break ties. ```R # Select rows with minimum cyl, including all ties mtcars |> slice_min(cyl, n = 1) # Select exactly one row by disabling tie handling mtcars |> slice_min(cyl, n = 1, with_ties = FALSE) # Break ties using multiple variables mtcars |> slice_min(tibble(cyl, mpg), n = 1) ```