【问题标题】:R How to group_by, split or subset by row valuesR如何按行值分组,拆分或子集
【发布时间】:2020-10-31 08:15:59
【问题描述】:

这是从上一个问题继续R, how to group by row value? Split?

输入Dataframe的变化是

id = str_c("x",1:22)
val = c(rep("NO1", 2), "START", rep("yes1", 2), "STOP", "NO",
         "START","NO1", "START", rep("yes2", 3), "STOP", "NO1",
        "START", rep("NO3",3), "STOP", "NO1", "STOP")
data = data.frame(id,val)

预期输出是具有 val 列的数据框,如下所示-

val = c("START", rep("yes1", 2), "STOP", 
        "START","NO1", "START", rep("yes2", 3), "STOP",
        "START", rep("NO3",3), "STOP", "NO1", "STOP")

【问题讨论】:

  • 我不明白你的问题。你能解释一下为什么 x15 被丢弃了吗?
  • 我需要从 START 到 STOP 的 val 列。如果情况类似于 START NO1 START - 我需要从第一个 START 开始计算(如果情况是 STOP,那么最后一个 STOP)。在 x15 的情况下,它不在 START-STOP 范围内,因此我想忽略它

标签: r dataframe group-by subset


【解决方案1】:

简单地说,如果我们删除所有其他既不是 START 也不是 STOP 的条目,那么,如果 START 是第一个 START 或前面有一个 STOP,则它是一个有效的起点;类似地,如果 STOP 是最后一个 STOP 或随后有 START,则 STOP 是有效端点。考虑这个函数:

valid_anchors <- function(x) {
  are_anchors <- x %in% c("START", "STOP")
  id <- seq_along(x)[are_anchors]
  x <- x[are_anchors]
  start_pos <- which(x == "START" & c("", head(x, -1L)) %in% c("", "STOP"))
  stop_pos <- which(x == "STOP" & c(tail(x, -1L), "") %in% c("", "START"))
  list(id[start_pos], id[stop_pos])
}

然后只需应用您在上一篇文章中获得的相同功能

ind <- valid_anchors(data$val)

data[sort(unique(unlist(mapply(`:`, ind[[1]], ind[[2]])))), ]

输出

    id   val
3   x3 START
4   x4  yes1
5   x5  yes1
6   x6  STOP
8   x8 START
9   x9   NO1
10 x10 START
11 x11  yes2
12 x12  yes2
13 x13  yes2
14 x14  STOP
16 x16 START
17 x17   NO3
18 x18   NO3
19 x19   NO3
20 x20  STOP
21 x21   NO1
22 x22  STOP

【讨论】:

    猜你喜欢
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2021-07-21
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    相关资源
    最近更新 更多