Reputation: 31
I am trying to subset some data in R between specific points. Specifically, I am looking to only return data after the minimum value and before the maximum value. My data set is similar to what is below. So, I'm trying to subset points data after point 8 and before data point 20.
x1
1. 4
2. 4
3. 5
4. 5
5. 5
6. 4
7. 3
8. 0
9. 1
10. 2
11. 2
12. 3
13. 3
14. 4
15. 5
16. 6
17. 6
18. 7
19. 8
20. 6
21. 4
22. 2
So the expected output would be
8. 0
9. 1
10. 2
11. 2
12. 3
13. 3
14. 4
15. 5
16. 6
17. 6
18. 7
19. 8
I have tried
min <- min(x1)
max <- max(x1)
newdata <- subset(x1,x1<max|x1>min)
This returns the exact same data set. Which makes sense because all values are above the minimum or below the maximum. But is there a way to get the data specifically from the minimum to the maximum and exclude the data before the minimum and after the maximum? Thanks
Upvotes: 3
Views: 228
Reputation: 434
ycw´s solution is clearly more elegant, but I´ll give you mine
cdata<-as.data.frame(c(4,4,5,5,5,5,4,3,0,1,2,2,3,3,4,5,6,6,7,8,6,4,2))
min <- min(cdata)
max <- max(cdata)
rowmax<- max(which(cdata == max))
rowmin<- min(which(cdata == min))
if (rowmax>rowmin){
cdata<-cdata[rowmin:rowmax,, drop=FALSE]
} else{cdata<-cdata[rowmax:rowmin,, drop=FALSE]}
Upvotes: 1