sasir sasir - 8 months ago 37
R Question

How to mark if value continuosly frozen more than or equal to 4 times

Hi i have a df as below

How to create column "rep" if values in value columns repeats >=4 tome

we can create RLE_created column with below code

df$RLE_created<-sequence(rle(as.character(df[,grep("Value",colnames(df))]))$lengths)

Value RLE_created rep
1 1
3 1 y
3 2 y
3 3 y
3 4 y
7 1
8 1
8 2
9 1 y
9 2 y
9 3 y
9 4 y
9 5 y


Thanks in advance

Answer Source

One option would be

library(data.table)
setDT(df)[, rep :=  c("", "Y")[(.N >= 4)+1], Value]

NOTE: It is better not to use function names for object names

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download