繁体   English   中英

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

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

好的,我只是想根据标识符/字符列重命名嵌套 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,最后一个小节的 Sepal.Widht 应该重命名为 virginica。

您可以远离公式符号:

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

reprex 包(v0.2.1) 于 2019 年 3 月 10 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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