简体   繁体   中英

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.

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))
library("tidyverse")

rename_func <- function(data, Species) {
  Species <- as.character(Species)
  data %>%
    rename(!!Species := Sepal.Length)
}

iris2 <- as_tibble(iris) %>%
  nest(-Species) %>%
  group_by(Species) %>%
  mutate(
    data = map2(data, Species, rename_func))

iris2 %>% filter(Species == "setosa") %>% unnest() %>% head(1)
#> # A tibble: 1 x 5
#> # Groups:   Species [3]
#>   Species setosa Sepal.Width Petal.Length Petal.Width
#>   <fct>    <dbl>       <dbl>        <dbl>       <dbl>
#> 1 setosa     5.1         3.5          1.4         0.2
iris2 %>% filter(Species == "versicolor") %>% unnest() %>% head(1)
#> # A tibble: 1 x 5
#> # Groups:   Species [3]
#>   Species    versicolor Sepal.Width Petal.Length Petal.Width
#>   <fct>           <dbl>       <dbl>        <dbl>       <dbl>
#> 1 versicolor          7         3.2          4.7         1.4
iris2 %>% filter(Species == "virginica") %>% unnest() %>% head(1)
#> # A tibble: 1 x 5
#> # Groups:   Species [3]
#>   Species   virginica Sepal.Width Petal.Length Petal.Width
#>   <fct>         <dbl>       <dbl>        <dbl>       <dbl>
#> 1 virginica       6.3         3.3            6         2.5

Created on 2019-03-10 by the reprex package (v0.2.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM