Error using str_replace_all and str_squish

Hi there,

I am having some trouble getting the str_replace_all and str_squish to work and not sure why.

My actual survey dataset contains 470 columns, where the column names are filled with periods. So, I am trying to:

  • remove all the periods and replace them with a space;
  • remove any additional spaces; and
  • add a question mark at the end of the column names.

This is the code I am working with (using the iris dataset as a test):

data(iris)

indicators <- iris %>%
  rename_with(
    stringr::str_replace_all("\\.", " ") %>%
      stringr::str_squish() %>%
      stringr::str_replace_all("$", "?")
  )
#> Error in iris %>% rename_with(stringr::str_replace_all("\\.", " ") %>% : could not find function "%>%"

Created on 2022-09-30 with reprex v2.0.2

I saw in this post (str_replace_all problem) that it appears that I am missing a 'replacement value' but I thought the " " in the stringr::str_replace_all("\\.", " ") was the replacement value (i.e. white space)?

You pass iris as the first argument of rename_with. The second argument has to be a function. I put a ~ in front of your series of stringr functions to make it act like an anonymous function. I could then refer to the column being acted on as .x and used that as the first argument of str_replace_all. The arguments of str_replace_all are str_replace(string, pattern, replacement) and your were missing string.

library(dplyr)
data(iris)

indicators <- iris %>%
  rename_with(
    ~stringr::str_replace_all(.x,"\\.", " ") %>%
      stringr::str_squish() %>%
      stringr::str_replace_all("$", "?")
  )
colnames(indicators)
#> [1] "Sepal Length?" "Sepal Width?"  "Petal Length?" "Petal Width?" 
#> [5] "Species?"

Created on 2022-09-29 with reprex v2.0.2

Thanks! That worked!! I didn't know about ~ and .x - that's really useful :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.