根据另一列的顺序在一个因子内创建子组

时间:2019-01-24 03:24:39

标签: r tidyverse data-manipulation

我正在尝试根据特定列在一个因素内创建子组。这是一个名为“ test”的示例数据集,与我正在使用的数据集相似。

structure(list(old.id = c("A", "A", "A", "A", "A", "A", "A", 
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C", "C"
), id.number = c(1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4, 5, 6, 1, 2, 
3, 4, 1, 2, 3), X = c(0.859207813394842, 0.636238617960869, 0.507899267816508, 
0.400124367809121, 0.867246955862074, 0.620089503630128, 0.493032629079145, 
0.702937523522877, 0.897875765710176, 0.360667580073056, 0.931321208973492, 
0.298666640389948, 0.94444119643156, 0.223731238077921, 0.705733544607941, 
0.354808093410256, 0.196606367677969, 0.67764700709383, 0.510474776312792, 
0.214473998493235), Y = c(44, 41, 43, 61, 41, 51, 55, 34, 41, 
63, 15, 77, 57, 73, 60, 71, 73, 16, 50, 19), Z = c(322, 349, 
395, 300, 368, 357, 385, 306, 385, 377, 323, 335, 314, 372, 372, 
362, 311, 301, 332, 314), Factor1 = c("Y", "N", "N", "N", "Y", 
"N", "Y", "Y", "Y", "Y", "Y", "N", "N", "Y", "Y", "Y", "N", "Y", 
"N", "N"), Factor2 = c("L", "M", "H", "L", "H", "L", "L", "M", 
"H", "H", "H", "M", "L", "H", "H", "H", "L", "H", "L", "M")), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

我的两个主要目标:

  1. 将“ old.id”列匿名化
  2. 使用由old.id列和“ id.number”列定义的新“ new.id”创建事件链

如果不添加“ id.number”列的排序,我可以通过使用

轻松地使ID匿名
library(tidyverse)
new_test=test %>%  mutate(new_id=group_indices(.,old.id))

我无法确定如何对结果进行分组并使用“ id.number”分配新的ID。以下是我希望得到的结果。

structure(list(old.id = c("A", "A", "A", "A", "A", "A", "A", 
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C", "C"
), id.number = c(1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4, 5, 6, 1, 2, 
3, 4, 1, 2, 3), new.id = c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 
3, 4, 4, 4, 4, 5, 5, 5), X = c(0.859207813394842, 0.636238617960869, 
0.507899267816508, 0.400124367809121, 0.867246955862074, 0.620089503630128, 
0.493032629079145, 0.702937523522877, 0.897875765710176, 0.360667580073056, 
0.931321208973492, 0.298666640389948, 0.94444119643156, 0.223731238077921, 
0.705733544607941, 0.354808093410256, 0.196606367677969, 0.67764700709383, 
0.510474776312792, 0.214473998493235), Y = c(44, 41, 43, 61, 
41, 51, 55, 34, 41, 63, 15, 77, 57, 73, 60, 71, 73, 16, 50, 19
), Z = c(322, 349, 395, 300, 368, 357, 385, 306, 385, 377, 323, 
335, 314, 372, 372, 362, 311, 301, 332, 314), Factor1 = c("Y", 
"N", "N", "N", "Y", "N", "Y", "Y", "Y", "Y", "Y", "N", "N", "Y", 
"Y", "Y", "N", "Y", "N", "N"), Factor2 = c("L", "M", "H", "L", 
"H", "L", "L", "M", "H", "H", "H", "M", "L", "H", "H", "H", "L", 
"H", "L", "M")), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

因此,如果我们查看“ old.id” = A和“ id.number”字段何时循环回到1,则它将定义新的事件“链”并分配一个“ new.id”数字。有60列,大约500,000行,任何解决方案都需要扩展到数百万行。我希望使用一个整洁的解决方案,以便可以将其添加到现有的整洁管道中,但是我很感激任何可行的方法。谢谢

1 个答案:

答案 0 :(得分:0)

在上面的评论中,listist提供了一个非常好的解决我的问题的方法。在这里:

df$new.id <- cumsum(df$id.number == 1) or in dplyr, df <- df %>% mutate(new.id = cumsum(id.number == 1))