You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:含-1、1、0的向量峰组识别及起止位置提取优化

问题:识别向量中的连续1/-1峰组并获取起止位置

我有如下形式的向量:

1 -1  1  1 -1 -1 -1  1 -1

需要识别其中由连续1和连续-1组成的峰组,即1, -1、1, 1, -1, -1, -1、1, -1,最终要获取这些峰组的起始位置(比如1, 3, 8)和结束位置(比如3, 8, 10)。

现有方法的问题

用rle()函数无法得到理想结果:

r <- rle(c(1, -1, 1, 1, -1, -1, -1, 1, -1))
which(rep(x = diff(sign(diff(c(-Inf, r$values, -Inf)))) == -2, times = r$lengths))
# [1] 1 3 4 8

结果里的4是不需要的。

包含0的有效场景

向量中可能包含不与1、-1交替的0,以下都是需要支持的有效场景:

  • 0 0 1 -1 1 1 -1 -1 -1 1 -1
  • 1 -1 1 1 -1 -1 -1 1 -1 0 0
  • 0 0 1 -1 1 1 -1 -1 -1 1 -1 0 0
  • 1 -1 0 0 1 1 -1 -1 -1 1 -1

背景:替换慢速的pracma::findpeaks()代码

我正尝试替换pracma::findpeaks()里的一段运行极慢的代码:

xc <- paste(as.character(sign(diff(x))), collapse = "")
xc <- gsub("1", "+", gsub("-1", "-", xc))
xc <- gsub("0", zero, xc)
peakpat <- sprintf("[+]{%d,}[-]{%d,}", nups, ndowns)
rc <- gregexpr(peakpat, xc)[[1]]
if (rc[1] < 0) return(NULL)
x1 <- rc
x2 <- rc + attr(rc, "match.length")
attributes(x1) <- NULL
attributes(x2) <- NULL

我尝试用整数运算改写,目前的实现如下,但仍存在问题:

xc2 <- sign(diff(x))
changepoints <- cumsum(abs(c(1, diff(xc2) != 0)))
group_size <- tabulate(changepoints)
lag <- c(NA, group_size[seq_len(length(group_size) - 1)])
lead <- c(group_size[2:length(group_size)], NA)
rc1 <- rep(0L, length(xc2))
rc1[xc2 == 1 & rep(group_size >= nups, group_size) & rep(lead >= ndowns, group_size)] <- 1L
rc1[xc2 == -1 & rep(group_size >= ndowns, group_size) & rep(lag >= nups, group_size)] <- -1L
rc1_backup <- rc1
rc1[rc1 == 0] <- -1
x1 <- which(diff(c(0, rc1)) > 0)
rc1 <- rc1_backup
rc1[rc1 == 0] <- 1
x2 <- which(diff(c(rc1, 0)) > 0) + 1

内容的提问来源于stack exchange,提问作者nathaneastwood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:24:56