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

时间:2019-03-09 19:45:16

标签: r dplyr tidyr purrr rlang

好吧,我只是想根据标识符/字符列重命名嵌套小标题内的一列:

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

我尝试使用ensym中的rlang以及!!:=的各种组合,但均未成功。 也就是说,数据列中的第一个小标题应将Sepal.Width列重命名为setosa,第二个小标题应重命名为杂色,最后一个小标题Sepal.Widht应重命名为virginica。

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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(v0.2.1)于2019-03-10创建