I am trying to create a new column in a tibble which is the concatenation of several string columns. These columns have names that all fit a pattern... in particular, they all start with the same substring. I am trying every combination of selecting inside and outside mutate
, with each of paste
, str_c
, and unite
I can think of, to no avail.
Reprex:
library(tibble); library(dplyr)
df <- tibble(
include1 = c("a", "b", "c"),
include2 = c("d", "e", NA),
include3 = c("f", "g", "h"),
include4 = c("i", NA, NA),
ignore = c("j", "k", "l")
)
df
# A tibble: 3 x 5
include1 include2 include3 include4 ignore
<chr> <chr> <chr> <chr> <chr>
1 a d f i j
2 b e g NA k
3 c NA h NA l
I'm trying code that looks like variants of:
df %>%
mutate(included = str_c(starts_with("include"), " | ", na.rm = TRUE)) %>%
select(ignore, included)
with the expected output:
# A tibble: 3 x 2
ignore included
<chr> <chr>
1 j a | d | f | i
2 k b | e | g
3 l c | h
How may I achieve this?