Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add +1 (>1) after every time a condition is met

(sorry, really don't know how to better phrase this question)

I have a column "have" with 1s and 0s. I want to create a new column "want" where, each time a 1 has occurred, the value of 0 increases to 2, then 3, then 4, etc. 0 should never be 1.

Example:

data <- data.frame(have = (c('0', '0', '0', '0', '1', '0', '1', '0', '0', '1')), 
                   want = (c('0', '0', '0', '0', '1', '2', '1', '3', '3', '1')))                       
like image 692
user303287 Avatar asked Dec 06 '25 10:12

user303287


1 Answers

You could do:

data <- data.frame(have = (c('0', '0', '0', '0', '1', '0', '1', '0', '0', '1')))  

data$want <- cumsum(as.numeric(data$have)) + 1
data$want[data$want == "1"] <- "0"
data$want[data$have == "1"] <- "1"

data
#>    have want
#> 1     0    0
#> 2     0    0
#> 3     0    0
#> 4     0    0
#> 5     1    1
#> 6     0    2
#> 7     1    1
#> 8     0    3
#> 9     0    3
#> 10    1    1

Created on 2022-04-06 by the reprex package (v2.0.1)

like image 79
Allan Cameron Avatar answered Dec 09 '25 01:12

Allan Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!