coalesce_multi: Coalesce Multiple Columns

View source: R/coalesce_multi.R

coalesce_multiR Documentation

Coalesce Multiple Columns

Description

Coalesce columns matching the LHS when splitting by pattern. Columns are coalesced from left to right as they appear in df

Usage

coalesce_multi(df, pattern = stringr::fixed("."), noisy = TRUE)

Arguments

df

a data frame

pattern

pattern to split column names along using stringr::str_split_fixed

noisy

Do you want messages about the columns being coalesced?

Value

a data frame with coalesced columns

Note

Columns that do not contain pattern but match another column after splitting will STILL be coalesced. In the example, the columns c(value, value.x, value.y) are coalesced when (pattern = stringr::fixed('.').

Examples

# Let's say you have two two data sets about birds
# and you want to combine them to make a more complete version
# while prioritizing the woods data over the feeder data
woods = tibble::tibble(
  bird = c('Northern Flicker', 'Chesnut-backed Chickadee', 'California Quail'),
  group_size = c(NA, NA, 2L),
  food = c('bugs', NA, 'seeds')
)

feeder = tibble::tibble(
  bird = c('Northern Flicker','Chesnut-backed Chickadee', 'Evening Grosbeak'),
  group_size = c(1L, 8L, 13L),
  food = c('seeds', NA, NA)
)

# See what they look like when joined on "bird"
dplyr::full_join(
  x = woods,
  y = feeder,
  by = 'bird'
)

# When we coalesce multi, it first looks for non-missing values
# from the woods (.x) and then from the feeder (.y):
dplyr::full_join(
  x = woods,
  y = feeder,
  by = 'bird'
) |>
  coalesce_multi()

# Note that it can coalesce values with
# different separators and even no suffix:
dplyr::full_join(
  x = woods,
  y = feeder,
  by = 'bird',
  suffix = c('', '~feeder')
) |>
  coalesce_multi(pattern = '~')

svenhalvorson/SvenR documentation built on Aug. 25, 2023, 1:31 p.m.