R: Subsetting on increasing value to max excluding the decreasing

一笑奈何 提交于 2019-12-20 03:41:14

问题


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.


回答1:


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]



回答2:


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


来源:https://stackoverflow.com/questions/31571588/r-subsetting-on-increasing-value-to-max-excluding-the-decreasing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!