Contributor
Posts: 40

# Count number of times variables changes from 0 to 1

I have a dataset of 25000 records with this layout;

ID    DOC25    DOC26   DOC27    DOC28   DOC29   ........  DOC48

1           0             1              1           0                1                      0

DOC25-DOC48 are montly counts which have 0 if the person was on the streets, 1 if incarcerated

DOC25 corresponds to January 2013

DOC48 corresponds to December 2014

I want to count how many times was a person incarcerated but if the person remains in prison longer than 1 month, the following months will be 1 as well until it changes to 0 when release, here in December 2014. So I want to keep track only of the first time the value changes

thanks!

Super User
Posts: 23,724

## Re: Count number of times variables changes from 0 to 1

The logic is if the variable value doesn't equal the previous value. You've had previous answers that demonstrate a loop over the values

and declaring an array so this should be enough to get started.

``If doc(i) ne doc(i-1) then flag_count+1;``
Super User
Posts: 6,774

## Re: Count number of times variables changes from 0 to 1

Sounds like this should do it within a DATA step:

array docs {*} doc25-doc48;

incarcerated=0;

do i=2 to 24;

if docs{i}=1 and docs{i-1}=0 then incarcerated + 1;

end;

This assumes that if DOC25=1 then you don't want to count it as an incarceration.  If that's wrong, it's easy enough to change.

Posts: 5,529

## Re: Count number of times variables changes from 0 to 1

Astounding wrote:

This assumes that if DOC25=1 then you don't want to count it as an incarceration.  If that's wrong, it's easy enough to change.

The alternative would require changing

incarcerated=0;

to

incarcerated=docs{1};

PG
Super User
Posts: 9,599

## Re: Count number of times variables changes from 0 to 1

As an alternative:

```data want;
doc1=0; doc2=1; doc3=1; doc4=0; doc5=1;
test=count(cats(of doc:),"01");
run;```
Posts: 5,529

## Re: Count number of times variables changes from 0 to 1

Or again, if you want to count initial incarcerations

``````data want;
doc1=0; doc2=1; doc3=1; doc4=0; doc5=1;
test=count(cats("0", of doc:),"01");
run;``````
PG
Discussion stats
• 5 replies
• 431 views
• 3 likes
• 5 in conversation