ksing
ksing

Reputation: 67

R: Subsetting on increasing value to max excluding the decreasing

I have a number of trials where one variable increases to a max of interest then decreases back to a starting point. How would I go about just retaining the observations with the increasing values to max. Thanks.

For example

Trial A B C
    1 2 4 1
    1 4 3 2
    1 3 7 3
    1 3 3 2
    1 4 1 1
    2 4 1 1
    2 6 2 2
    2 3 1 3
    2 1 1 2
    2 7 3 1
    ...

So we would check max on C and retain as follows,

Trial A B C
    1 2 4 1
    1 4 3 2
    1 3 7 3
    2 4 1 1
    2 6 2 2
    2 3 1 3
    ...

Ultimately I'll have a low cut off value as well as varying perhaps what I mean by max but essentially the above is the aim.

Upvotes: 2

Views: 114

Answers (2)

David Arenburg
David Arenburg

Reputation: 92302

Probably not the most efficient solution, but here is an attempt using data.table

library(data.table)
setDT(df)[, .SD[1:which.max(C)], by = Trial]
#    Trial A B C
# 1:     1 2 4 1
# 2:     1 4 3 2
# 3:     1 3 7 3
# 4:     2 4 1 1
# 5:     2 6 2 2
# 6:     2 3 1 3

Or for some efficiency gain

indx <- setDT(df)[, .I[1:which.max(C)], by = Trial]
df[indx$V1]

Upvotes: 3

Shenglin Chen
Shenglin Chen

Reputation: 4554

library(dplyr)
df%>%group_by(Trial)%>%slice(1:max(C))

Upvotes: -1

Related Questions