0

I'd like to apply a character replacement to all columns of a tibble. I can do it for one column:

starwars %>% mutate(name = str_replace_all(name, "-", ""))

But I do not understand how to generalise to with across():

starwars %>% mutate(
  across(everything(),
    str_replace_all("-", "")
    )
  )

Is it necessary to use the purr package here?

Dario Lacan
  • 1,099
  • 1
  • 11
  • 25

2 Answers2

1

You almost had it. Use the dot notation to dynamically pass all columns specified in the everything() command to your string function.

library(tidyverse)
starwars %>%
  mutate(across(everything(),
         ~str_replace_all(., "-", "")))
deschen
  • 10,012
  • 3
  • 27
  • 50
1

Another option would be to use an anonymous function, which I personally find more intuitive and flexible than the dot notation:

starwars %>% mutate(
  across(everything(),
    function(x) str_replace_all(x,"-", "")
    )
  )
user438383
  • 5,716
  • 8
  • 28
  • 43