Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce a binary variable that takes value of 0 before the last non-zero value of another variable and 1 after it

Tags:

r

Given the variable

a <- c(1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0) 

I would like to mark the last non-zero value to produce a variable that takes value of 0 before the benchmark and 1 after it. In this case

b <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)

A simple command that allows to mark the last non-zero value of a a column is

tail(which(a!=0),1) 

But how to create the variable I need conditional on such benchmark? Any help would be much appreciated!

like image 364
another_newbie Avatar asked Dec 01 '25 09:12

another_newbie


2 Answers

One option could be:

+(cumsum(a) == max(cumsum(a)))

 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1

Or:

+(cumsum(a) == sum(a))
like image 75
tmfmnk Avatar answered Dec 03 '25 23:12

tmfmnk


We can use which to get the position, index where a is 1, wrap with max to return the last position, create a logical vector with sequence of 'a' and coerce to binary (+)

+(seq_along(a) >= max(which(a == 1)))
#[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1

Or use Position

+(seq_along(a) >= Position(function(x) x == 1, a, right = TRUE))
like image 31
akrun Avatar answered Dec 04 '25 01:12

akrun



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!