当重命名嵌套的tibble R中的数据列时,Unquoting无法在mutate和map2中找到变量

问题描述 投票:2回答:2

好的,我只是想根据标识符/字符列重命名嵌套tibble中的列:

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)))

但是这会返回错误:

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

我尝试过使用ensymrlang以及!!:=的所有组合都没有成功。这是数据列中的第一个元素应该将Sepal.Width列重命名为setosa,第二个重命名为versicolor,最后一个tupble Sepal.Widht应该重命名为virginica。

r dplyr tidyr purrr rlang
2个回答
1
投票

你可以改掉公式表示法:

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))

0
投票
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

reprex package创建于2019-03-10(v0.2.1)

© www.soinside.com 2019 - 2024. All rights reserved.