1

I have the following tibble

  tib <- tibble(AAA111 = rnorm(3), 
               AAA222 = rnorm(3), 
               BBB5 = rnorm(3), 
               BBB3456=rnorm(3))

I want to change the component of column names such that "AAA" becomes "M" and "BBB" becomes "W". I can do this outside purrr or a loop by the following

tib %>%
    rename_with(~str_replace(.x, "AAA", "M"), .cols = starts_with("AAA")) %>%
    rename_with(~str_replace(.x, "BBB", "W"), .cols = starts_with("BBB"))

But how do I achieve this in a map function or a loop?

Note I received some information from the following post. Purrr map with rename_with

user438383
  • 5,716
  • 8
  • 28
  • 43
Andrew
  • 111
  • 4

1 Answers1

0

No need to map or loop, just use rename_all() in conjunction with str_replace_all() (replacements may also be more complex since the patterns to be replaced are (by default) interpreted as regular expressions)

require(tidyverse)

tib <- tibble(AAA111 = rnorm(3), AAA222 = rnorm(3), BBB5 = rnorm(3), BBB3456 = rnorm(3))

# define vector of replacements 
replacement <- c('BBB' = 'W', 'AAA' = 'M')

# use str_replace_all which can handle a named vector
rename_all(tib, ~ str_replace_all(.x, replacement))
#> # A tibble: 3 × 4
#>     M111   M222    W5  W3456
#>    <dbl>  <dbl> <dbl>  <dbl>
#> 1 -0.487  0.210 -1.08 -0.158
#> 2 -0.391  1.39   1.40 -0.292
#> 3 -1.08  -0.722  1.21 -0.782

Created on 2022-08-16 by the reprex package (v2.0.1)

maike
  • 220
  • 1
  • 6