0

In this block of SAS data step code I am setting a Table from an SQL query called TEST_Table. This table contains multiple columns including a larger section of columns titled PREFIX_1 to PREFIX_20. Each column starts with PREFIX_ and then an incrementing number from 1 to 20.

What I would like to do is iteratively cycle through each column and analyze the value of that column.

Below is an example of what I am trying to go for. As you can see I would like to create a variable that increases on each iteration and then I use that count value as a part of the variable name I am checking.

data TEST_Data;
  set TEST_Table;
  retain changing_number;
  
  changing_number=1;
  do while(changing_number<=20);    
    if PREFIX_changing_number='BAD_IDENTIFIER' then do;
      PREFIX_changing_number='This is a bad part';
    end;
  end;  

run;

How would be the best way to do this in SAS? I know I can do it by simply checking each value individually from 1 to 20.

if PREFIX_1 = 'BAD_IDENTIFIER' then do;
  PREFIX_1 = 'This is a bad part';
end;
if PREFIX_2 = ...

But that would be really obnoxious as later I will be doing the same thing with a set of over 40 columns.

Ideas?

SOLUTION

data TEST_Data;
    set TEST_Table;
    
    array SC $ SC1-SC20;
    
    do i=1 to dim(SC);    
      if SC{i}='xxx' then do;
         SC{i}="bad part";
      end;   
    end;  
run;

Thank you for suggesting Arrays :)

2
  • 1
    You can remove several parts of that with no difference. The {*} is unneeded if you specify the variables explicitly. The i=1; does absolutely nothing. I recommend highly using dim(SC) rather than 20 as it makes your code easier to maintain as well. Commented Nov 15, 2012 at 22:18
  • @Joe Those changes work better than a charm. Commented Nov 16, 2012 at 18:58

1 Answer 1

1

You need to look up Array processing in SAS. Simply put, you can do something like this:

data TEST_Data;
  set TEST_Table;
  *retain changing_number; Remove this - even in your code it does nothing useful;
  array prefixes prefix:; *one of a number of ways to do this;
  changing_number=1;
  do while(changing_number<=20);    
    if prefixes[changing_number]='BAD_IDENTIFIER' then do;
       prefixes[changing_number]='This is a bad part';
    end;
  end;  

run;

A slightly better loop is:

do changing_number = 1 to dim(prefixes);
... loop ...
end;

As that's all in one step, and it is flexible with the number of array elements (dim = number of elements in the array).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.