Create conditional with counter in a column

Asked

Viewed 32 times

3

I have a basis that I need to know which number is greater than 100, but if I have a sequence of values greater than 100 I need the column to accumulate the value of 1 in 1, I added an output figure of how it should look.

base::set.seed(400)
a <- base::round(stats::runif(30, min = 50, max = 300),2)

inserir a descrição da imagem aqui

1 answer

5


The problem can be solved with a trick diff/cumsum, that gives vector segments a which comply with the condition, followed by ave/seq_along, to give integer sequences. And to put zeros in the right places, multiply this result by the condition f.

f <- a > 100
g <- cumsum(c(FALSE, diff(f) != 0))
b <- ave(g, g, FUN = seq_along)
res <- cbind(a, b = b * f)

head(res, 15)
#           a b
# [1,]  87.49 0
# [2,]  96.35 0
# [3,] 232.70 1
# [4,] 141.15 2
# [5,] 282.40 3
# [6,] 150.45 4
# [7,] 111.85 5
# [8,] 175.59 6
# [9,] 118.41 7
#[10,] 122.31 8
#[11,]  72.02 0
#[12,] 195.78 1
#[13,] 251.33 2
#[14,] 204.64 3
#[15,] 241.09 4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.