## Using arrays to see if consecutive elements are the same

Solved
Occasional Contributor
Posts: 12

# Using arrays to see if consecutive elements are the same

I have a data set with the variables VentUnit1-VentUnit151,

I have been attempting to use arrays to flag observations in which VentUnit(i) in ('8N-ICU, '8S-NSICU') and VentUnit(i+1) in ('8N-ICU, '8S-NSICU') such as Line#4 in the screenshot.  I'm having trouble trying to code this with do loops and have a feeling I'm taking the wrong approach.

Any thoughts?

Thanks.

Accepted Solutions
Solution
2 weeks ago
Super User
Posts: 23,754

## Re: Using arrays to see if consecutive elements are the same

``do i=1 to i=151``

This is likely wrong and should  be:

``do i=1 to dim(unit)-1;``

Because you're checking i+1 you can only go up to one less than the dimension and you can use the DIM() function to get the number of elements.

You may also want to set CHECK to 0 at the beginning of the loop but otherwise that seems correct.

``````data lines5;
set lines4;

array Unit (*) VentUnit1-VentUnit151;

check=0;

do i=1 to dim(unit)-1;
if Unit(i) in ('8N-ICU','8S-NSICU') and Unit(i+1) in ('8N-ICU','8S-NSICU') then check+1;
end;

run;``````

All Replies
Super User
Posts: 23,754

## Re: Using arrays to see if consecutive elements are the same

I'm having trouble trying to code this with do loops and have a feeling I'm taking the wrong approach.

Can you show us the code you're using?

@malmario wrote:

I have a data set with the variables VentUnit1-VentUnit151,

I have been attempting to use arrays to flag observations in which VentUnit(i) in ('8N-ICU, '8S-NSICU') and VentUnit(i+1) in ('8N-ICU, '8S-NSICU') such as Line#4 in the screenshot.  I'm having trouble trying to code this with do loops and have a feeling I'm taking the wrong approach.

Any thoughts?

Thanks.

Occasional Contributor
Posts: 12

## Re: Using arrays to see if consecutive elements are the same

``````data lines5;
set lines4;

array Unit (*) VentUnit1-VentUnit151;

do i=1 to i=151;
if Unit(i) in ('8N-ICU','8S-NSICU') and Unit(i+1) in ('8N-ICU','8S-NSICU') then check+1;
end;

run;``````
Solution
2 weeks ago
Super User
Posts: 23,754

## Re: Using arrays to see if consecutive elements are the same

``do i=1 to i=151``

This is likely wrong and should  be:

``do i=1 to dim(unit)-1;``

Because you're checking i+1 you can only go up to one less than the dimension and you can use the DIM() function to get the number of elements.

You may also want to set CHECK to 0 at the beginning of the loop but otherwise that seems correct.

``````data lines5;
set lines4;

array Unit (*) VentUnit1-VentUnit151;

check=0;

do i=1 to dim(unit)-1;
if Unit(i) in ('8N-ICU','8S-NSICU') and Unit(i+1) in ('8N-ICU','8S-NSICU') then check+1;
end;

run;``````

Occasional Contributor
Posts: 12

## Re: Using arrays to see if consecutive elements are the same

Thank you Reeza!

☑ This topic is solved.