Pedro Alencar
Pedro Alencar

Reputation: 1089

R - Replace sequence values by its maximum in a column

I am with a small problem and hope someone can help me.

I have a dataframe like this:

df <- data.frame(foo = 1:20, bar = c(0,0,1,0,0,0,1,2,0,0,1,2,3,0,0,0,1,2,3,4))

and what to have a result like this:

df_result <-  data.frame(foo = 1:20, bar = c(0,0,1,0,0,0,2,2,0,0,3,3,3,0,0,0,4,4,4,4))

How do I do this without using a while loop?

Upvotes: 0

Views: 112

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

Using ave in base R :

with(df, as.integer(bar > 0) * (ave(bar, cumsum(bar == 0), FUN = max)))
#[1] 0 0 1 0 0 0 2 2 0 0 3 3 3 0 0 0 4 4 4 4

where cumsum(bar == 0) is used to create groups, ave is used to calculate max in each group and as.integer(bar > 0) is to keep value which are 0 as 0.

Upvotes: 4

Related Questions