Tom
Tom

Reputation: 379

How can I use multiple stringr functions with mutate & across?

I want to mutate across two or more specified columns and make all strings lower case and replace spaces with an underscore in the same step.

For example...

Starting dataset

> tribble(
+   ~colA, ~colB,
+   "a b C",   "De F",
+   "A c B",   "d E f",
+   "A B C",   "D Ef"
+ )

# A tibble: 3 × 2
  colA  colB 
  <chr> <chr>
1 a b C De F 
2 A c B d E f
3 A B C D Ef 

Should end up looking like this

# A tibble: 3 × 2
  colA  colB 
  <chr> <chr>
1 a_b_c de_f 
2 a_c_b d_e_f
3 a_b_c d_ef

So far I have

dat %>% 
  mutate(across(.cols = c(colA, colB), .fns = str_to_lower(str_replace(., " ", "_"))))

But I get the following error message

Error in `mutate()`:
! Problem while computing `..1 = across(...)`.
Caused by error in `across()`:
! `.fns` must be NULL, a function, a formula, or a list of functions/formulas.
Run `rlang::last_error()` to see where the error occurred.
Warning message:
Problem while computing `..1 = across(...)`.
ℹ argument is not an atomic vector; coercing 

Upvotes: 0

Views: 1237

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

It's a syntax error. Use ~ to specify the .fns and use .. Moreover, str_replace would only replace the 1st value, to replace all the values use str_replace_all.

library(dplyr)
library(stringr)

dat %>% 
  mutate(across(.cols = c(colA, colB), 
                .fns = ~str_to_lower(str_replace_all(., " ", "_"))))

# A tibble: 3 × 2
#  colA  colB 
#  <chr> <chr>
#1 a_b_c de_f 
#2 a_c_b d_e_f
#3 a_b_c d_ef 

Upvotes: 2

Related Questions