Reputation: 1901
I want to rename a couple of variables that have a certain prefix using str_replace. I am running into the issue depicted with the REPREX bellow:
test <- tibble::tribble(~pre_a, ~pre_b, ~c,
1,2,3,
4,5,6)
test %>%dplyr::rename_at(., dplyr::vars(starts_with('pre')),
stringr::str_replace(., pattern = 'pre', replacement ='PRE'))
error:
Error in get(.x, .env, mode = "function") : object 'c(1, 4)' of mode 'function' was not found In addition: Warning message: In stri_replace_first_regex(string, pattern, fix_replacement(replacement), : argument is not an atomic vector; coercing
The issue is solely with str_replace, because if I a base R function it will work:
test %>%dplyr::rename_at(., dplyr::vars(starts_with('pre')), toupper)
Note: I don't just want to convert to uppercase, so I need to use the str_replace function.
Upvotes: 0
Views: 707
Reputation: 389325
You need to use the ~
notation when using a custom function.
library(dplyr)
test %>%
dplyr::rename_at(dplyr::vars(starts_with('pre')),
~stringr::str_replace(., pattern = 'pre', replacement ='PRE'))
Also rename_at
is now replaced with rename_with
.
test %>%
dplyr::rename_with(~stringr::str_replace(.,pattern = 'pre',replacement ='PRE'),
dplyr::starts_with('pre'))
# A tibble: 2 x 3
# PRE_a PRE_b c
# <dbl> <dbl> <dbl>
#1 1 2 3
#2 4 5 6
Upvotes: 2