简体   繁体   中英

How to create a counter that groups repeats into the same value while ignoring NAs

I dataframe with more than 5000 rows of a simulation. My problem is like this

rex <- c("Positive", "Negative", NA, "Positive", "Negative", "Negative")

I would like to create a counter that returns:

1,2,NA,3,4,4

as the result, where the repetition of the same value, has the same counter.

Appreciate any help. Thank you,

Best

here we could make use of data.table::rleid eg

library(data.table)
rex <- c("Positive", "Negative", NA, "Positive", "Negative", "Negative",NA,"Negative")
idx <- !is.na(rex)

if rex <- c("Positive", NA, "Positive") should output 1, NA, 1

as.numeric(replace(rex, idx, rleid(rex[idx])))
[1]  1  2 NA  3  4  4 NA  4

if rex <- c("Positive", NA, "Positive") should output 1, NA, 2

as.numeric(replace(rex, idx, rleid(rleid(rex)[idx])))
[1]  1  2 NA  3  4  4 NA  5

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