如何计算波形中脉冲的宽度?

时间:2019-01-24 07:38:48

标签: r

我需要计算波形中脉冲的宽度。这些脉冲遍布整个波形。

我正在尝试计算两个连续值之间的差,如果它超过一个值(例如一个数字),那么我将确定该点为脉冲的起点并找到一个达到与之前相同水平的点&我认为这是脉搏的终点。一旦有了起点和终点,我就会计算宽度(这里是这两个点之间的点数)

3 个答案:

答案 0 :(得分:2)

ggpmisc()可以提供一些解决方案。需要对span值进行一些优化

wave <- c(1, 2, 1, 1.3, 1.2, 1, 2, 1, -25, -23, -24, -25, -24, -23, -26, -23, -17, -11, 2, 1, 1, 2)
wave = data.frame(wave = wave)

library(tidyverse)
#> Warning: package 'tibble' was built under R version 3.5.2
library(ggpmisc)
#> For news about 'ggpmisc', please, see https://www.r4photobiology.info/
#> For on-line documentation see https://docs.r4photobiology.info/ggpmisc/

with_valley <- 
   ggplot_build(
     ggplot(wave, aes(seq_along(wave), wave)) + geom_line() +
  stat_valleys(aes(seq_along(wave), wave), span = 10) 
   )
#> span increased to next odd value:  11


values <- with_valley$data[[2]]

values[2,"xintercept"]-values[1,"xintercept"]
#> [1] 6

reprex package(v0.2.1)于2019-01-24创建

答案 1 :(得分:2)

这里有可能使用vapply

解决任务
starting_points <- which(c(abs(diff(pulse)) > 25L, FALSE))
res <- vapply(starting_points, function (k) {
  starting_value <- pulse[k]
  end_point <- min(intersect(which(pulse == starting_value), (k+1):length(pulse)))
  width <- end_point - k + 1
  c(start = k, end = end_point, width = width)
}, numeric(3))

# Results
res
#       [,1]
# start    8
# end     20
# width   13

# And here is result with a little more data
# setting pulse <- rep(pulse, 3L)
t(res)
#      start end width
# [1,]     8  20    13
# [2,]    30  42    13
# [3,]    52  64    13

了解数据

pulse <- c(1, 2, 1, 1.3, 1.2, 1, 2, 1, -25, -23, -24, -25, -24, -23, -26, -23, -17, -11, 2, 1, 1, 2)

答案 2 :(得分:0)

这是带有通用for()循环的解决方案。请注意,这对于大数据可能很慢并且无效。

# example vector
x <- c(1, 2, 1, 1.3, 1.2, 1, 2, 1, -25, -23, -24, -25, -24, -23, -26, -23, -17, -11, 2, 1, 1, 2)

# initialize data frame with columns start (starting position of pulse), end (end position of pulse) and width (width of pulse)
pulsewidth <- data.frame(start = numeric(),
                         end = numeric(),
                         width = numeric())

# initialize temporary saving element for starting position
temp <- NA

# loop over position 2 to end of vector, compare lagged values, store position if pulse starts
for(i in 2:length(x)){
  if(abs(x[i] - x[i-1]) >= 25){
    temp <- i-1 # here you could use temp <- i instead, depending on your definition
  }
  if(!is.na(temp)){
    if(x[i] >= x[temp]){
      pulsewidth[nrow(pulsewidth)+1,] <- c(temp, i, i - temp)
      temp <- NA
    }
  }
}

结果:

> pulsewidth
  start end width
1     8  19    11