AHAMES
AHAMES

Reputation: 71

How to remove rows in a dataframe if they rows are not in order

I have this dataframe:

      x  year bucket       price
1  2108  2010     7       100000 
2  2108  2010     2        95000 
3  2108  2010     3        93000
4  2108  2010    14        92000
5  2108  2010    13        91000
6  2108  2010     8        90500
7  2108  2010    10        89000
8  2108  2010     5        88000
9  2108  2010     9        87000
10 2108  2010    11        86000 
11 2108  2010    16        85000 
12 2108  2010    12        84000
13 2108  2010     1        83000 

I arranged it according to price, but the buckets are not in the correct order, I want to remove them so that it becomes like this:

      x  year bucket       price
1  2108  2010     7       100000 
4  2108  2010    14        92000
11 2108  2010    16        85000

Is there a direct way to do it in R

Upvotes: 1

Views: 37

Answers (1)

GKi
GKi

Reputation: 39687

You can use cummax for subseting.

x[x$bucket == cummax(x$bucket),]
#      x year bucket  price
#1  2108 2010      7 100000
#4  2108 2010     14  92000
#11 2108 2010     16  85000

Data:

x <- read.table(header=TRUE, text="      x  year bucket       price
1  2108  2010     7       100000 
2  2108  2010     2        95000 
3  2108  2010     3        93000
4  2108  2010    14        92000
5  2108  2010    13        91000
6  2108  2010     8        90500
7  2108  2010    10        89000
8  2108  2010     5        88000
9  2108  2010     9        87000
10 2108  2010    11        86000 
11 2108  2010    16        85000 
12 2108  2010    12        84000
13 2108  2010     1        83000 ")

Upvotes: 6

Related Questions