FatimaS
FatimaS

Reputation: 49

small dplyr syntax clarification

Not sure why i am still stuck at this problem and tried researching around and i can't believe i am still stuck at it

How can i integrate 'between','or','and' in the same filter statement?

I thought a comma would be 'and' and | would be or so i went with the below filter statement. Not giving the intended result.

sample

d<-structure(list(minsell= c(31,-31,0,0),
                  maxsell= c(31,-31,0,0),
                  minbuy= c(0,0,31,31),
                  maxbuy= c(0,0,0,31)), class = "data.frame", row.names = c(NA, -4L))

intended output enter image description here

Code line i am using

testing<-testing%>%dplyr::filter(((between(minsell, 1, -31)),(between(maxsell, 1, -31)))|((between(minbuy, 31, -1))|(between(maxbuy, 31, -1))))

Upvotes: 2

Views: 40

Answers (1)

akrun
akrun

Reputation: 887098

If we want to wrap multiple expressions to be taken as a single block, then it is always recommended to wrap those in a () to evaluate as a single block. Otherwise, due to precedence of operators (most languages have its own set or operator precedence, assignment precedence, etc), it can lead to different outcome. The between function from dplyr is a shortcut for x >= left & x <= right i.e. it includes the bounds as well. So, make sure the values are adjusted

d %>% 
    filter((between(minsell, -31, 1) & between(maxsell, -31, 1)) | 
           (between(minbuy, 1, 32) & between(maxbuy, 0, 30)))

Upvotes: 2

Related Questions