Вот решение с общим циклом 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