Search code examples
rdplyrtidyrpurrrrlang

Unquoting fails to find variable in mutate and map2 when renaming column of data in nested tibble R


Ok, I'm just trying to rename a column inside a nested tibble based on an identifier/character column:

MWE:

library(magrittr)
iris %>% 
  tibble::as_tibble() %>%
  tidyr::nest(-Species) %>%
  dplyr::mutate(
    Species = as.character(Species),
    data = purrr::map2(data, Species,
                       ~dplyr::rename(.x, !!.y := Sepal.Width)))

but this returns the error:

Error in quos(..., .named = TRUE) : object '.y' not found

I have tried using ensym from rlang and all sort of combinations of !! and := without success. That is the first tibble in the data column should have the Sepal.Width column renamed to setosa, the second to versicolor, and for the last tibble Sepal.Widht should be renamed to virginica.


Solution

  • You could switch away from the formula notation:

    library(magrittr)
    irisNest <- iris %>%
      tibble::as_tibble() %>%
      tidyr::nest(-Species) %>%
      dplyr::mutate(Species = as.character(Species))
    
    f <- function(x,y) {dplyr::rename(x, !!y := Sepal.Width)}
    
    irisCheck <- dplyr::mutate(irisNest,
                  data = purrr::map2(data, Species, f))