dplyr::summarise 中的句点 (`.`) 用于在组内引用表

问题描述 投票:0回答:1

我有下表:

# Inputs
require(dplyr)

set.seed(123)

df <- tibble(g = rep(x = c("A", "B", "C"), times = c(3, 5, 7)),
             a = sample(x = 1:100, size = 15), 
             b = sample(x = 1:100, size = 15))

df

# A tibble: 15 × 3
   g         a     b
   <chr> <int> <int>
 1 A        87     8
 2 A        35    51
 3 A        40    74
 4 B        30    50
 5 B        12    98
 6 B        31    86
 7 B        97    76
 8 B        64    84
 9 C        14    46
10 C        71    17
11 C        67    62
12 C        23    92
13 C        79    54
14 C        85    35
15 C        37    79

我还定义了一个函数(对于本例来说非常简单),它接受整个数据框并返回单个数值:

# Function
myFUN <- function(x){
  mean(x$a + x$b)
}

我正在寻找的是应用

group_by
summarise
函数来获取包含每组结果的表格。

我认为这可以像执行以下操作一样简单:

# What I got (incorrect results)
df %>%  
  
  group_by(g) %>% 
  
  summarise(res = myFUN(.))

# A tibble: 3 × 2
  g       res
  <chr> <dbl>
1 A      112.
2 B      112.
3 C      112.

但是正如您所看到的,所有结果 (

res
) 值都是相同的,因为
.
指的是整个初始表,而不是每个组中的子集表。

我留下了一个使用循环的预期结果的示例:

# Expected
out <- list()
for(i in unique(df$g)){
  out[[length(out) + 1]] <- tibble(g = i,
                                   res = df %>% filter(g == i) %>% myFUN)
}

out |> bind_rows()

# A tibble: 3 × 2
  g       res
  <chr> <dbl>
1 A      98.3
2 B     126. 
3 C     109.
r dplyr tidyverse
1个回答
0
投票

我没有得到你预期的结果,但我认为这给了你你想要的。

.x
取代了
.
,因为
group_map
需要一个带有两个参数的函数。

df %>% 
  group_by(g) %>% 
  group_map(
    function(.x, .y) {
      .x %>% 
        summarise(res = mean(a + b)) %>% 
        add_column(g = .y$g, .before = 1)
    }
  ) %>% bind_rows()
# A tibble: 3 × 2
  g       res
  <chr> <dbl>
1 A      78.7
2 B     101. 
3 C     117. 
© www.soinside.com 2019 - 2024. All rights reserved.