SAS - determine if all of the variables equal to specific values?

Viewed 44

Here's an example of the dataset I'm working on:

id var1 var2 var3 var4
1 1 2 1 1
2 1 1 1 1
3 1 2 3 1

I want to create a new variable, "ind", to indicate if there is any variable doesn't equal to 1 or 2. In this example, id1 and id2 would have ind=1. id3 would have ind=0, as it has a 3.

Expected table:

id var1 var2 var3 var4 ind
1 1 2 1 1 1
2 1 1 1 1 1
3 1 2 3 1 0

Here's what I have tried:

data want;
    set have;

    array alpha_column[*] var1--var4;
    array bin_column[30] _TEMPORARY_;
    do i = 1 to dim(bin_column);
        bin_column[i] = (alpha_column[i] = 1); 
    end;
    ind= (sum(of bin_column[*]) > 0);
    drop i;
run;

The problem is that it cannot determine var=1 or 2, but var=1 only. Thank you!

2 Answers

Set the flag variable to the opposite or what you want before the DO loop and then reset it when the condition is met. You can stop looping as soon as the condition is met.

data have ;
  input id var1-var4;
cards;
1 1 2 1 1
2 1 1 1 1
3 1 2 3 1
;

data want;
  set have;
  array list var1-var4;
  ind = 1 ;
  do i = 1 to dim(list) until(ind=0);
    if list[i] not in (1 2) then ind=0;
  end;
  drop i;
run;

Results

Obs    id    var1    var2    var3    var4    ind

 1      1      1       2       1       1      1
 2      2      1       1       1       1      1
 3      3      1       2       3       1      0

Check if the max of the series is greater than 2 or the minimum is less than 1.

data want;
    set have;

    array alpha_column[*] var1--var4;
    ind = 1;
    if max(of alpha_column(*))>2 or min(of alpha_column(*))<1 then ind=0;


run;

Edit: this won't handle missing values, it will ignore them if they occur in the series but could be modified to account for that if it's an issue.

Related