简体   繁体   中英

Count by group with condition (in R data.table)

Consider a dataset that consists of ID and Val .

# dataset
ID Val Counter
 1   2       1
 1   4       2
 1  NA       2
 1  13       3
 1  12       4
 2  NA       0
 2  33       1
 2   5       2
 2   5       3

A counter per subgroup can be added by dt[, normal_counter := 1:.N, by=ID] . I am looking for a counter that is not incremented when there is an NA value (see counter in example above).

This is a cumulative sum of non- NA values by group, so:

dat[, cntr := cumsum(!is.na(Val)), by=ID]
dat
#   ID Val Counter cntr
#1:  1   2       1    1
#2:  1   4       2    2
#3:  1  NA       2    2
#4:  1  13       3    3
#5:  1  12       4    4
#6:  2  NA       0    0
#7:  2  33       1    1
#8:  2   5       2    2
#9:  2   5       3    3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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