【问题标题】:Repeating Sequence extraction from a R list / data column从 R 列表/数据列中重复序列提取
【发布时间】:2016-04-27 19:34:02
【问题描述】:

我有一系列事件时间戳,基于这些时间戳我在 R 中创建了如下的事件处理流字符串:

  1. A->B->C->D->E
  2. A->C->D->E
  3. B->C->D
  4. A->E

等等……

我有 50 个这样的流程组合。我想列出流程中可用的每个唯一转换,如下所示:

  1. A->B
  2. A->C
  3. A->E
  4. B->C
  5. C->D

等等。

我不知道如何在 R 中做到这一点。任何指导/解决方案都会非常有帮助

谢谢。

【问题讨论】:

  • 您的预期输出是不可预测的,但如果您想将它们分解为单独的步骤,您可以使用s <- strsplit('A->B->C->D->E', '->')[[1]] ; sapply(seq_along(s[-1]), function(x){paste(s[x], s[x+1], sep = '->')})
  • 您的解决方案有所帮助。我会调整它以适应我的代码流。谢谢
  • 哦,我知道你现在想要什么了。已编辑,其中s 是流字符串的向量:s <- strsplit(s, '->') ; unique(unlist(lapply(s, function(x){sapply(seq_along(x[-1]), function(y){paste(x[y], x[y+1], sep = '->')})}))) sort 如果您愿意。

标签: r substring


【解决方案1】:

按照@alistaire,在->上拆分传入的字符串,然后记录每个序列中的元素个数。

t <- strsplit(s, "->", fixed=TRUE)
len <- lengths(t)

现在,取消列出 t 并使用长度的累积总和删除最后一个或第一个元素以获得“来自”和“到”节点

u <- unlist(t)
clen = cumsum(len)
from <- u[-clen]
to <- u[-(1 + c(0, clen[-length(clen)]))]

fromto粘贴在一起,找出唯一值,然后排序

sort(unique(paste(from, to, sep="->")))

作为单个函数

f0 <- function(s) {
    t <- strsplit(s, "->", fixed=TRUE)
    clen <- cumsum(lengths(t))

    u <- unlist(t)
    from <- u[-clen]
    to <- u[-(1 + c(0, clen[-length(clen)]))]
    sort(unique(paste(from, to, sep="->")))
}

为您的样品

s <- c("A->B->C->D->E",
       "A->C->D->E",
       "B->C->D",
       "A->E")

输出是

> f0(s)
[1] "A->B" "A->C" "A->E" "B->C" "C->D" "D->E"

枚举整个数据集上所有观察到的单步转换。这就是你想要的吗?

@alistaire 的解决方案,泛化为处理多个字符串

f1 <- function(s) {
    t <- strsplit(s, "->", fixed=TRUE)
    res <- lapply(t, function(s) {
        sapply(seq_along(s[-1]), function(x) {
            paste(s[x], s[x+1], sep = '->')
        })
    })
    sort(unique(unlist(res)))
}

身份和基准测试的简单测试是

> library(microbenchmark)
> identical(f0(s), f1(s))
[1] TRUE
> microbenchmark(f0(s), f1(s))
Unit: microseconds
  expr     min      lq      mean   median       uq     max neval cld
 f0(s)  45.379  47.010  48.62282  47.6240  48.4005 120.063   100  a 
 f1(s) 179.509 182.168 184.41779 182.9585 183.7985 234.607   100   b

对于大型数据集f0() 会快得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-13
    • 2017-12-15
    • 1970-01-01
    • 2021-07-19
    • 2018-04-08
    • 2021-10-10
    • 1970-01-01
    • 2016-07-26
    相关资源
    最近更新 更多