Search code examples
rdplyr

Why does combination of rename_with() and str_replace() fail?


I am trying to replace "Abundance." in the names of the columns in my tibble. I am using the following approach:

Error when using dplyr rename_at and stringr str_replace together to rename columns

xx <- structure(list(Sequence = c("HSEAATAQR", "GAAAHPDSEEQQQR"), Abundance..126 = c(12.3, 12.2), Abundance..127N = c(17.7, 13.5), Abundance..127C = c(11.9, 11.3)), row.names = 1:2, class = "data.frame") 
rename_with(xx, str_replace(., pattern = "Abundance.", replacement = ""), contains("Abundance."))

I get the error: "Error in vctrs::vec_size_common(string = string, pattern = pattern, replacement = replacement, : object '.' not found"

I understand that it means that the str_replace() function does not receive the string argument that I am trying to pass to it as ".", but it does seem to work in the example mentioned above

Error when using dplyr rename_at and stringr str_replace together to rename columns


Solution

  • You are missing a ~operator. Use the following

    xx %>% 
      rename_with(~str_replace(., pattern = "Abundance.", replacement = ""), contains("Abundance."))
    

    The functions argument must be either

    • a named function (e.g. a function defined before, see example later)
    • an anonymous function (like \(x) str_replace(x, pattern = "Ab", ""))
    • or a formula (indicated by ~)

    Named Functions

    To use rename_with with a named function, you might use the following:

    delete_abundance <- function(x) {
      str_replace(x, pattern = "Abundance.", replacement = "")
    }
    
    xx %>%
      rename_with(delete_abundance, contains("Abundance."))