This function performs a tidyverse-friendly string concatenation. It takes a data frame or tibble and a selection of columns, concatenates the string values in each row, and returns the concatenated strings as a vector.
Usage
str_c_tidy(
...,
sep = "",
collapse = NULL,
na.rm = FALSE,
if_all_na = c("empty", "NA")
)Arguments
- ...
<
tidy-select> tidyselect expression indicating character columns vectors or columns coercible to character.- sep
separator to insert between input vectors.
- collapse
optional character string to combine results into a single string.
- na.rm
logical. Remove missing values before concatenating? Treatment of
NAs is similar tostr_c_narm()and differs from behavior ofpaste()andstringr::str_c(). See Details ofstr_c_narm().- if_all_na
what to do if
na.rm = TRUEand all values in a row areNA."empty", the default, returns an empty string."NA"returnsNA. Ignored ifna.rm = FALSE.
Examples
df <- tibble::tribble(
~x, ~y, ~z,
"a", "b", "c",
"d", NA, "f",
"g", "h", NA
)
df %>% dplyr::mutate(combined = str_c_tidy(x:z))
#> # A tibble: 3 × 4
#> x y z combined
#> <chr> <chr> <chr> <chr>
#> 1 a b c abc
#> 2 d NA f NA
#> 3 g h NA NA
df %>% dplyr::mutate(combined = str_c_tidy(x:z, na.rm = TRUE))
#> # A tibble: 3 × 4
#> x y z combined
#> <chr> <chr> <chr> <chr>
#> 1 a b c abc
#> 2 d NA f df
#> 3 g h NA gh
