【问题标题】:identifying rows in data frame that exhibit patterns识别数据框中显示模式的行
【发布时间】:2015-03-29 01:24:29
【问题描述】:

下面我有 3 列的代码:组字段、商店的打开/关闭字段以及商店打开的 3 个月的滚动总和。我也有所需的解决方案输出。

可以将我的数据集视为员工可用性。您可以假设每一行都是不同的时间段(小时、日、月、年等)。在打开/关闭列中,我有员工是否在场。 3 个月滚动列是前几行的总和。

我要确定的是此滚动总和列中的非零值遵循对于该特定组至少 3 个零行 /em>。虽然此数据集中不存在,但您可以假设可能存在多个零“间隙”。

 structure(list(Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
 2L, 2L, 2L), .Label = c("A", "B"), class = "factor"), X0_closed_1_open =      c(0L, 
1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), X3month_roll_open = c(0L, 
0L, 1L, 2L, 2L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 2L, 0L, 1L, 1L, 1L, 
0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L), desired_solution = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("no", "yes"), class ="factor")), .Names = c("Group", "X0_closed_1_open", "X3month_roll_open", "desired_solution"), class = "data.frame", row.names = c(NA, 
 -26L))

【问题讨论】:

    标签: r dataframe pattern-matching match


    【解决方案1】:

    一个选项是:

    res <- unsplit(
             lapply(split(df1, df1$Group), function(x) {
              rl <- with(x,rle(X3month_roll_open==0))
              indx <- cumsum(c(0,diff(inverse.rle(within.list(rl, 
                        values[values] <- lengths[values]>=3)))<0))
              x$Flag <- indx!=0 & x[,3]!=0
              x}),
            df1$Group)
    

    注意:代替“是/否”,使用“真/假”来缓和子​​集可能会更好。

     identical(c('no', 'yes')[res$Flag+1L], as.character(res$desired_solution))
     #[1] TRUE
    

    【讨论】:

      猜你喜欢
      • 2017-04-27
      • 2019-03-21
      • 2017-08-19
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 2012-12-29
      • 2019-05-11
      • 2017-01-31
      相关资源
      最近更新 更多