【问题标题】:is there a R code for group_by and combinations是否有 group_by 和组合的 R 代码
【发布时间】:2020-07-22 09:18:54
【问题描述】:

我正在寻找可以计算每组总数中 2 的组合的 R 代码。

library(dplyr)
    id<-c(1,1,1,1,2,2,2,2,3,3,3,3)
    sex<-c(1,1,1,1,1,1,1,1,1,1,1,1)
    ds<-data.frame(id,sex)
    out1<-ds %>% group_by(id) %>% summarise(n=n())
    

我的输出应该是

 id<-c(1,2,3)
    n<-c(4,4,4)
    ncomb2<-c(6,6,6)
    

谢谢

【问题讨论】:

  • 我不明白你的任务背后的逻辑。能详细解释一下吗?
  • 请改写问题,因为“计算每组总数的组合”不清楚
  • 亲爱的罗伯特,我已经编辑了
  • 亲爱的马丁,任务是按 ID 计算每个组中的总数,我已经完成了,我现在想要每个总数中的 2 个组合
  • 你能解释一下为什么n_comb_id1_and_2 = 6的逻辑吗?

标签: r dplyr combn


【解决方案1】:

我不确定下面的代码是否是你所追求的

out1 <- ds %>%
    group_by(id) %>%
    summarise(n = n()) %>%
    mutate(ncomb2 = choose(n,2))

这样

> out1
# A tibble: 3 x 3
     id     n ncomb2
  <dbl> <int>  <dbl>
1     1     4      6
2     2     4      6
3     3     4      6

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多