tidyverse concatenate characters across columns does not work with c_across

Viewed 154

I have the following data:

dat <- data.frame(sheet      = c("a", "b", "c"),
                  condition1 = c("k", "l", "m"),
                  condition2 = c("x", "y", "z"))

I now want to create a new column using the tidyverse that concatenastes these columns. However, I always get an error.

library(tidyverse)

new_dat %>%
  rowwise() %>%
  mutate(marker = str_c(c_across(c(sheet, starts_with("condition"))), sep = "/")) %>%
  ungroup()

Error: Problem with `mutate()` input `marker`.
x Input `marker` can't be recycled to size 1.
i Input `marker` is `str_c(c_across(c(sheet, starts_with("condition"))), sep = "/")`.
i Input `marker` must be size 1, not 3.
i Did you mean: `marker = list(str_c(c_across(c(sheet, starts_with("condition"))), sep = "/"))` ?
i The error occurred in row 1.

Any suggestion/help?

Expected output:

  sheet condition1 condition2 marker
1     a          k          x  a/k/x
2     b          l          y  b/l/y
3     c          m          z  c/m/z

Note: I alyo tried the code without using the rowwise part and using across instead of c_across (and adapting the syntax for across), but I'm getting a similar error. Replacing str_c by paste0 also doesn't work.

EDIT: deleted the x column from the input data since it doesn't add any value.

3 Answers

Use collapse, not sep:

dat %>%
  rowwise() %>%
  mutate(marker = str_c(c_across(c(sheet, starts_with("condition"))), 
                        collapse = "/")) %>%
  ungroup()

# A tibble: 3 x 5
  sheet condition1 condition2     x marker
  <fct> <fct>      <fct>      <dbl> <chr> 
1 a     k          x              1 a/k/x 
2 b     l          y              2 b/l/y 
3 c     m          z              3 c/m/z 

You can see the difference between sep and collapse with this simple example (it's easier to show than explain):

str_c(letters[1:3], letters[4:6], sep = "_")
# "a_d" "b_e" "c_f"

str_c(letters[1:3], letters[4:6], collapse = "_")
# "ad_be_cf"

With a combination of dplyr and purrr, you could do:

dat %>%
 mutate(marker = pmap(across(c(sheet, starts_with("condition"))), paste, sep = "/"))

  sheet condition1 condition2 x marker
1     a          k          x 1  a/k/x
2     b          l          y 2  b/l/y
3     c          m          z 3  c/m/z

You can use tidyr's unite :

tidyr::unite(dat, marker, sheet, starts_with('condition'), 
             sep = '/', remove = FALSE)

#  marker sheet condition1 condition2 x
#1  a/k/x     a          k          x 1
#2  b/l/y     b          l          y 2
#3  c/m/z     c          m          z 3
Related