r - 识别 R 数据框列中的数字或字符序列

标签 r dataframe dplyr tidyr zoo

mydf <- tibble::tribble(
   ~seq, ~flag,
      0,     0,
      0,     0,
      0,     0,
      1,     1,
      1,     1,
      7,     1,
      1,     1,
      3,     1,
      2,     1,
      1,     1,
      1,     1,
      0,     1,
      0,     1,
      0,     0,
      0,     0,
      1,     1,
      1,     1,
      7,     1,
      1,     1,
      3,     1,
      2,     1,
      1,     1,
      1,     1,
      0,     1,
      0,     1,
      0,     0,
      0,     0,
      2,     0
)

我有一个带有序列列的数据框。如何创建一个二进制标志来标记任何特定的数字序列?我的示例序列是 1、1、7、1、3、2、1、1、0、0。

最佳答案

library(zoo)
match_seq <- c(1, 1, 7, 1, 3, 2, 1, 1, 0, 0)
is_start <- rollapply(mydf$seq, length(match_seq), function(x) all(x == match_seq))
inds <- sapply(which(is_start), `+`, seq_along(match_seq) - 1)

mydf$flag2 <- as.numeric(1:nrow(mydf) %in% inds)


#    seq flag flag2
# 1    0    0     0
# 2    0    0     0
# 3    0    0     0
# 4    1    1     1
# 5    1    1     1
# 6    7    1     1
# 7    1    1     1
# 8    3    1     1
# 9    2    1     1
# 10   1    1     1
# 11   1    1     1
# 12   0    1     1
# 13   0    1     1
# 14   0    0     0
# 15   0    0     0
# 16   1    1     1
# 17   1    1     1
# 18   7    1     1
# 19   1    1     1
# 20   3    1     1
# 21   2    1     1
# 22   1    1     1
# 23   1    1     1
# 24   0    1     1
# 25   0    1     1
# 26   0    0     0
# 27   0    0     0
# 28   2    0     0

在没有library(zoo)的情况下计算is_start的一种方法是

subseqs <- 
  sapply(seq(0, nrow(mydf) - length(match_seq)), 
         function(i) mydf$seq[i + seq_along(match_seq)])

is_start <- colMeans(subseqs == match_seq) == 1

关于r - 识别 R 数据框列中的数字或字符序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54885338/

相关文章:

r - 在数据框中每行选择一个单元格

python : How to find the count of empty cells in one column based on another column element wise?

r - Dplyr:过滤系列中日期的最后一个条目

r - 在滑动窗口中汇总满足条件的交易

r - R中按条件映射的值

r - 使用 httr 进行网页抓取会出现 xml_nodeset 错误

r - 如何将向量 append 到 R 中的向量列表而不诉诸索引?

r - 在 R 中循环数据帧,直到满足特定条件

r - 检查一个数据帧的值是否以精确的顺​​序存在于另一个数据帧中

python - 从系列更改索引创建 Pandas 数据框