【问题标题】:Apply a function to all pairs in the same group将函数应用于同一组中的所有对
【发布时间】:2019-10-16 02:46:28
【问题描述】:

我想将一个函数应用于同一组中的所有项目对,例如

示例输入:

Group  Item   Value  
A      1       89   
A      2       76  
A      3       2  
B      4       21  
B      5       10  

所需的输出是同一组中所有项目的函数输出的向量。

例如如果函数是:

addnums=function(x,y){  
  x+y  
}

那么所需的输出将是:

165, 91, 78, 31

我曾尝试在 dplyr 包中使用 summarise 来执行此操作,但这只能在输出为单个值时使用。

【问题讨论】:

  • 实际上它不是您提供的问题的重复项。他想要组中每一对的总和,而不是组的总和。
  • 是的,重新打开了问题。
  • 哦,对不起。错过了。谢谢@RonakShah

标签: r dplyr


【解决方案1】:

我们可以通过 data.table 使用 group by 选项

library(data.table)
setDT(df1)[, combn(Value, 2, FUN = sum), Group]
#   Group  V1
#1:     A 165
#2:     A  91
#3:     A  78
#4:     B  31

如果我们想使用 OP 帖子中的addnums

setDT(df1)[, combn(Value, 2, FUN = function(x) addnums(x[1], x[2])), Group]
 #  Group  V1
#1:     A 165
#2:     A  91
#3:     A  78
#4:     B  31

或使用tidyverse

library(dplyr)
library(tidyr)
df1 %>% 
  group_by(Group) %>%
  summarise(Sum = list(combn(Value, 2, FUN = sum)))  %>% 
  unnest
# A tibble: 4 x 2
#  Group   Sum
#  <chr> <int>
#1 A       165
#2 A        91
#3 A        78
#4 B        31

使用addnums

df1 %>% 
 group_by(Group) %>%
 summarise(Sum = list(combn(Value, 2, FUN = 
         function(x) addnums(x[1], x[2])))) %>% 
 unnest

或者使用base Raggregate

aggregate(Value ~ Group, df1, FUN = function(x) combn(x, 2, FUN = sum))

数据

df1 <- structure(list(Group = c("A", "A", "A", "B", "B"), Item = 1:5, 
    Value = c(89L, 76L, 2L, 21L, 10L)), class = "data.frame", row.names = c(NA, 
-5L))

【讨论】:

  • 谢谢,这很好用,但对我来说使用我定义的 addnums 函数而不是 sum 非常重要,有没有办法实现这一点?
  • @Helen 谢谢,我更新了帖子。我会保留组信息列以正确识别值
【解决方案2】:

我们可以为每个Group 提供split Value,然后使用combn 计算每对的sum

sapply(split(df$Value, df$Group), combn, 2, sum)

#$A
#[1] 165  91  78

#$B
#[1] 31

如果需要作为一个向量,我们可以使用unlist

unlist(sapply(split(df$Value, df$Group), combn, 2, sum), use.names = FALSE)
#[1] 165  91  78  31

如果您对tidyverse 使用我们可以做的相同逻辑的解决方案感兴趣

library(dplyr)
library(purrr)

df %>%
  group_split(Group) %>%
  map(~combn(.x %>% pull(Value), 2, sum)) %>% flatten_dbl

#[1] 165  91  78  31

【讨论】:

  • 我尝试自己执行此操作,但无法正常工作。为什么group_by() 在这种情况下不起作用? data %&gt;% group_by(Group) %&gt;% {apply(combn(Value, m=2), 2, sum)}
  • @Adamm hmmm...我不确定在这里使用apply 是否是正确的选择。
  • 谢谢,太好了!但是,我不太清楚如何修改它以与我的自定义函数 addnums 而不是内置函数 sum 一起使用。
  • @Helen 你可以像sapply(split(df$Value, df$Group), function(x) combn(x, 2, function(y) addnums(y[1], y[2])))一样使用它
猜你喜欢
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 2020-02-18
  • 2023-01-24
  • 2017-05-12
  • 2021-01-14
  • 1970-01-01
  • 2016-05-02
相关资源
最近更新 更多