Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check n previous/consecutive numbers of a value (v) of a variable in R

Tags:

r

If i have the following variable:

numbers<-c(1,2,3,-5,4,5,6,-5,1,2,1,1,1,1,7,1,1,1,8,1,1,1,1,1,1,1,1,1,1,9,10,11,12,13,14,15,1,1,1,5
,5,5,5,5,5,5,5,5,5,5,5,5,5,5,78,78,78,78,78,78,78,3,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,-5,0,0,0,0,0,-5,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,-5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-5,-5,0,0)

I first want to find all -5 values:

index<-which(numbers == -5)
[1]   4   8  95 101 135 150 151
value<-numbers[which(numbers == -5)]
[1] -5 -5 -5 -5 -5 -5 -5

What i now want to do is check the 5 values before and after the positions where -5 occurs and see if all values are equal 0 and if that is so keep the starting index of it (index) if not delete it from index:

So in the following case the desired result would be:

r
95 101 135

Well i have managed to solve the problem with two independent for loops and one if condition and one temporary list of 2 (one element saving the index numbers one the values) and a variable for storing the result.

But well Iam sure there is a better/shorter/faster result for that? Anyone any suggestions? In the best of cases I would prefer a base R answer if possible.

like image 561
Kitumijasi Avatar asked Dec 20 '25 16:12

Kitumijasi


2 Answers

which(
  stats::filter(numbers == 0L,#logical vector 
                c(rep(1, 5), 0, rep(1, 5)) #sum 5 preceding and following logical values
  ) == 10L & #10 TRUE values?
    numbers == -5L
)
#[1]  95 101 135
like image 67
Roland Avatar answered Dec 22 '25 07:12

Roland


Try

index[sapply(index, function(x) all(!numbers[setdiff(pmax(1,
       x-5):pmin(x+5, length(numbers)), x)]))]
#[1]  95 101 135
like image 20
akrun Avatar answered Dec 22 '25 08:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!