简体   繁体   English

如何根据特定条件查找首次出现

[英]How to find the first appearance based on certain criteria

I have the following proxy data and I am using data table. 我有以下代理数据,并且正在使用数据表。

Id         V1       V2
Aa         10      1000
Aa          20       90
Ab          20       90
Ab          20       90
Ab          20       100
As          50       90
As          300     150
As           150     0

I want to create another field to mark 1 for the first appearance of each ID in V2 that is greater than 0. Ie see ID Ab, it only gets marked 1 on its second entry. 我想创建另一个字段,将V2中每个ID的首次出现大于1标记为1。即看到ID Ab,它在第二个条目中仅标记为1。

So like the following: 因此,如下所示:

Id         V1       V2          Indicator
Aa         10      1000           1
Aa          20       90              0
Ab          20       0                0
Ab          20       90.             1
Ab          20       100.           0
As          50       90.             1
As          300     150.           0
As           150     0.              0
library( "data.table" )
df6[, id := 1:.N] # create unique row id
df6[, indicator := 0 ]  # assign 0 for all rows of indicator column
# find id values that pass the criteria and assign 1 to indicator column
df6[ id %in% df6[ V2 > 0 & V2 < 10000, .SD[1], by = .(Id)][, id], indicator := -1]
df6[ id %in% df6[ V2 >= 10000, .SD[1], by = .(Id)][, id], indicator := 1]
df6[ , id := NULL ] # remove id column
df6
#    Id  V1      V2 indicator
# 1: Aa  10    1000        -1
# 2: Aa  20      90         0
# 3: Ab  20       0         0
# 4: Ab  20      90        -1
# 5: Ab  20     100         0
# 6: As  50      90        -1
# 7: As 300     150         0
# 8: As 150       0         0
# 9: Ap  10 1000000         1  

Based on @Jaap's comment: 基于@Jaap的评论:

df6[, indicator := 0 ][
  df6[, .I[V2 > 0 & V2 < 10000][1], by = Id]$V1, indicator := -1][
    df6[, .I[V2 >= 10000][1], by = Id]$V1, indicator := 1]

Data: I added an extra row with a value more than 10K 数据:我添加了一个额外的行,其值超过10K

df6 <- fread('Id         V1       V2
    Aa         10      1000
             Aa          20       90
             Ab          20       0
             Ab          20       90
             Ab          20       100
             As          50       90
             As          300     150
             As           150     0
             Ap         10      1000000', header = TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM