1

I have such a dataset (a3), I want to select the rows of a3, the only condition is loc columns must be between Loc1 and Loc2. In my example output will be like a4. I use for loop but I want to use better functions in R such as apply or other

a3<-data.frame(ID=c(7,6,7,9,3,2),
  Loc=  c(22,25,28,32,35,37),
  Loc1= c(19,20,30,38,34,41),
  Loc2= c(14,28,31,41,37,1))
a4<-data.frame(ID=c(6,3),
  Loc=c(25,35),
  Loc1=c(20,34),
  Loc2=c(28,37))

1 Answers1

1

We can use >/< to create a logical vector in subset to subset the rows. As these operations are vectorized, can avoid the for loop

subset(a3, Loc >= Loc1 & Loc <= Loc2)
#  ID Loc Loc1 Loc2
#2  6  25   20   28
#5  3  35   34   37
akrun
  • 874,273
  • 37
  • 540
  • 662