r - magrittr `.` 代词和 rlang `.data` 代词是相同的,但那怎么可能呢?
问题描述
最后!TidyEval 变得越来越容易,这导致我在 magrittr.
代词和 rlang 代词之间进行了代词测试.data
。
library(tidyverse)
identical(head(iris, 2) %>% mutate(col = .$Species),
head(iris, 2) %>% mutate(col = .data$Species))
#> [1] TRUE
看那个。它们完全相同。除了他们可能不是。从上面链接的文章:
这 。magrittr 的代词在这里不合适,因为它代表整个数据框,而 .data 代表当前组的子集。
有什么区别?您可能在想,“只需阅读上面粘贴的那句话即可”。不幸的是,如果你能提供的话,我需要更多的解释。一些例子会很好。我想到的第一件事(上面的代码)将两个代词显示为“相同”。我在这里感觉到了矛盾。谢谢你。
解决方案
希望这将说明您问题中的引用:
``` r
library(dplyr)
iris[48:52,] %>%
group_by(Species) %>%
transmute(
Sepal.Length,
col0 = mean(Sepal.Length),
col1 = mean(.$Sepal.Length),
col2 = mean(.data$Sepal.Length))
#> # A tibble: 5 x 5
#> # Groups: Species [2]
#> Species Sepal.Length col0 col1 col2
#> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 setosa 4.6 4.97 5.66 4.97
#> 2 setosa 5.3 4.97 5.66 4.97
#> 3 setosa 5 4.97 5.66 4.97
#> 4 versicolor 7 6.7 5.66 6.7
#> 5 versicolor 6.4 6.7 5.66 6.7
```
!!sym(foo)
我认为有些人喜欢在没有体操的情况下使用它作为字符串传递参数:
col <- "Species"
iris[48:52,] %>%
mutate(
SPECIES1 = toupper(!!sym(col)),
SPECIES2 = toupper(.data[[col]]))
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species SPECIES1
#> 1 4.6 3.2 1.4 0.2 setosa SETOSA
#> 2 5.3 3.7 1.5 0.2 setosa SETOSA
#> 3 5.0 3.3 1.4 0.2 setosa SETOSA
#> 4 7.0 3.2 4.7 1.4 versicolor VERSICOLOR
#> 5 6.4 3.2 4.5 1.5 versicolor VERSICOLOR
#> SPECIES2
#> 1 SETOSA
#> 2 SETOSA
#> 3 SETOSA
#> 4 VERSICOLOR
#> 5 VERSICOLOR
对于它的价值,我总共不得不使用.data
3 次,当我这样做的时候,可能有更好的方法去做。我认为其中一两个具有ggplot2
.
你几乎可以忽略它的存在,.data
仍然可以成为一个非常体面的 tidyverse 忍者。
推荐阅读
- angular - HTTP 服务调用绑定到 HTML 元素
- node.js - AWS NodeJS Lambda 函数中的缓存内存
- github - !git push:-- 致命:无法读取“https://github.com”的用户名:没有这样的设备或地址||google colaboratory
- javascript - 是否可以使用摊牌解析 Markdown 文件中的标题?
- android - 离子图标不能与 Android 上的离子日期时间一起点击
- javascript - 如何在画布中创建撤消功能?
- fluentd - fluentd:多个过滤器和匹配的一个来源
- javascript - 如何在 for 循环中使用变量递增或递减?
- powershell - 避免在 GitHub 存储库中复制粘贴代码的最佳方法是什么
- extjs - EXTJS-Combobox(组合框列表选项未显示?)