【问题标题】:Count level within group_by hierarchy in dplyrdplyr 中 group_by 层次结构中的计数级别
【发布时间】:2017-06-06 05:22:24
【问题描述】:

我在 R 中有一个大型数据集,该数据集由来自单个案例的多个记录组织而成,嵌套在组中。这里有一个玩具示例:

d = data.frame(group = rep(c('control','patient'), each = 5), case = c('a', 'a', 'b', 'c', 'c', 'd','d','d','e','e'))

如果在 dplyr 链中,应用了group_by(group, case),如何创建一个列,以在组中按其大小写顺序对每一行进行编号?例如在下面的示例中,在第三列中,病例“a”是对照组中的第一个病例,病例“c”是第三个病例,但病例“d”的编号重置为 1,即患者组中的第一个病例.

  group case  number
control  a    1
control  a    1
control  b    2
control  c    3
control  c    3
patient  d    1
patient  d    1
patient  d    1
patient  e    2
patient  e    2

我可以通过使用“for”循环计算案例来了解如何做到这一点,但我想知道是否有办法在标准 dplyr 样式的操作链中实现这一点?

【问题讨论】:

  • d %>% group_by(group) %>% mutate(number = match(case, unique(case)))
  • @docendodiscimus 非常优雅。如果这是一个答案,我会接受它......

标签: r dplyr


【解决方案1】:
group_by(d, group) %>% 
   mutate(number= droplevels(case) %>% as.numeric)

【讨论】:

  • 哇,太好了。
【解决方案2】:

我们可以使用data.table

library(data.table)
setDT(d)[, numbers := as.numeric(factor(case, levels = unique(case))), group]

【讨论】:

  • 谢谢。这非常有效,尽管通常我更喜欢坚持使用(我认为是)更具可读性的 dplyr 语法。
【解决方案3】:

一种解决方案是:

library(dplyr)
library(tibble)

want<-left_join(d,
                d %>%
                  distinct(case) %>%
                  rownames_to_column(var="number") ,
                by="case")

# .. added later:
want2<-left_join(d,
                 bind_rows(
                   d %>%
                     filter(group=="control") %>%
                     distinct(case) %>%
                     rownames_to_column(var="number"),
                   d %>%
                     filter(group=="patient") %>%
                     distinct(case) %>%
                     rownames_to_column(var="number")),
                   by="case")

# I think this is less readable:
want3<-left_join(d,
                 bind_rows(by(d,d$group,function(x) x %>%
                                distinct(case) %>%
                                rownames_to_column(var="number"))),
                 by="case")

【讨论】:

  • 很好,但尽管它获得了部分方式(编号案例),但通过使用行名,编号不会在组变量的每个级别重新开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 2023-04-03
  • 2012-12-17
相关资源
最近更新 更多