带点(“.”)、“~”和竖线(%>%)运算符的 R 组合

R combinations with dot ("."), "~", and pipe (%>%) operator

我一直在寻找很多答案,但我仍然不能完全理解它们。比如最清楚的(here), among others (,2,)给出了点的各种用法的具体例子,但是我看不懂,比如这里的应用:

car_data <- 
  mtcars %>%
  subset(hp > 100) %>%
  aggregate(. ~ cyl, data = ., FUN = . %>% mean %>% round(2)) %>%
  transform(kpl = mpg %>% multiply_by(0.4251)) %>%
  print

#result:
  cyl   mpg  disp    hp drat   wt  qsec   vs   am gear carb    kpl
1   4 25.90 108.0 111.0 3.94 2.15 17.75 1.00 1.00 4.50 2.00 11.010
2   6 19.74 183.3 122.3 3.59 3.12 17.98 0.57 0.43 3.86 3.43  8.391
3   8 15.10 353.1 209.2 3.23 4.00 16.77 0.00 0.14 3.29 3.50  6.419

上面的代码来自 explanation for %>% in magrittr,我也在尝试理解管道运算符(我知道它会为您提供先前计算的结果,但我迷失在 aggregate 代码行,当它在同一个函数中混合 .%>% 时。

所以,我无法理解上面的代码是什么。我有结果(我把它放在上面)。但我不明白它是如何达到这个结果的,特别是 aggregate 代码行,它使用了点和 ~ 符号。我知道 ~ 表示 "all other variables",但是圆点是什么意思?它有其他含义或应用吗?以及特定函数中的管道运算符是什么?

该行以三种不同的方式使用 .

         [1]             [2]      [3]
aggregate(. ~ cyl, data = ., FUN = . %>% mean %>% round(2))

一般来说,您使用 . 将值从管道传递到您的函数的特定位置,但也有一些例外。一个例外是当 . 在公式中时。 ~ 用于在 R 中创建公式。管道不会改变公式的含义,因此它的行为就像没有任何转义一样。例如

aggregate(. ~ cyl, data=mydata)

那只是因为 aggregate 需要一个同时具有左侧和右侧的公式。所以 [1] 处的 . 只是表示 "all the other columns in the dataset." 这种用法与 m​​agrittr 完全无关。

[2] 处的 . 是作为管道传入的值。如果您有一个普通的 . 作为函数的参数,那么该值将被放置在那里。所以 subset() 的结果将转到 data= 参数。

magrittr 库还允许您使用 . 变量定义匿名函数。如果您有一个以 . 开头的链,它会被视为一个函数。所以

. %>% mean %>% round(2)

相同
function(x) round(mean(x), 2)

所以您只是在 [3]

处使用 . 创建自定义函数

由于有多个函数按顺序执行,因此一个选项是使用 compose

library(tidyverse)
f1 <- list(mean,  partial(round, digits = 2))
mtcars %>% 
    filter(hp > 100) %>% 
    group_by(cyl) %>% 
    summarise_all(list(~lift(compose)(f1)(.))) %>% 
    mutate(kpl = mpg * 0.4251) #multiply_by is a bit verbose

点在聚合语句中的三种用法:

  • aggregate.formula aggregateformula 方法指定了一个公式,其中左侧 (LHS) ~ 的右侧定义了要应用函数的变量,~ 的右侧定义了要分组的变量。它在公式中使用点来表示公式中未提及的所有其他变量。例如,使用具有列 lensuppdose 的内置 ToothGrowth 数据框,这些是相同的。我们按 supp 分组,而 mean 作用于 lendose.

    aggregate(. ~ supp, ToothGrowth, mean)
    aggregate(cbind(len, dose) ~ supp, ToothGrowth, mean)
    
  • RHS of pipe 当用在管道的右侧(RHS)时 magrittr 使用点来表示输入,即左侧的任何内容管道的手边。因此,这些是相同的:

    4 %>% sqrt(.) # use of dot on RHS
    sqrt(4)
    
  • 管道的 LHS 当用在管道的左侧时 magrittr 使用点来表示函数定义。例如,这两个函数定义都定义了一个对其参数求平方的函数:

    square1 <- . %>% .^2 # use of dot on LHS
    square2 <- function(x) x^2
    

也许题中的例子不带点最容易看出来:

mtcars0 <-  mtcars %>%
  subset(hp > 100)

aggregate(
  cbind(mpg,disp,hp,drat,wt,qsec,vs,am,gear,carb) ~ cyl,  # cbind(...) in place of .
  data = mtcars0, # mtcars0 in place of .
  FUN = function(x) round(mean(x), 2)) # instead of . %>% etc.