找到小于第一次出现值的值 [英] Finding any values less than the first occurrence of a value

查看:130
本文介绍了找到小于第一次出现值的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 dplyr 或DT来确定在第一次出现值后,任何后续值是否小于该给定值。

I am trying to use dplyr or DT to determine if, after the first occurrence of a value, any subsequent values are less than that given value.

所以如果我有一个数据框如下,

So if I have a data frame as below,

df2 <- data.frame(id=c(1,1,1,1,1,2,2,2,2,3,3,3,3,3,3),
             num=c(1,2,1,1,2,1,1,1,2,2,1,1,1,2,2))
df2$id <- as.factor(df2$id)

我想在第一次出现2后发现小于2的ID。例如,这将选择up id 1,因为第二行中有一个2,但是对于该id,后续行小于2)。

I want to find the id's that have an occurrence less than 2 after the first occurrence of 2. For example, this would pick up id 1, since there is a 2 in the second row, but for that id, there are subsequent rows less than 2).

任何想法?

推荐答案

听起来像一个工作?位置给我,虽然我不确定你想要什么输出:

Sounds like a job for ?Position to me, though I'm not sure what output you want exactly:

library(data.table)
setDT(df2)
df2[, Position(I,num==2) < Position(I,num < 2,right=TRUE,nomatch=FALSE), by=id]
#   id    V1
#1:  1  TRUE
#2:  2 FALSE
#3:  3  TRUE

 df2[, Position(I,num==2) < Position(I,num < 2,right=TRUE,nomatch=FALSE), by=id][,id[V1]]
#[1] 1 3
#Levels: 1 2 3

这篇关于找到小于第一次出现值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆