Netbrian
Netbrian

Reputation: 641

Retrieve Column Based On Data Step Variable

I'm writing a SAS job. For this SAS job, I need to do the following --

  1. Retrieve the value of the field ActiveColumn. This value will be the name of another column in the table.
  2. Set ActiveValue equal to the value of the field named by ActiveColumn.

Basically, I'm trying to write a version of this where I don't half to write out every column name beforehand --

Select(ActiveColumn);
  when ('CITY') ActiveValue = City;
  when ('STATE') ActiveValue = State;
  when ('ZIP') ActiveValue = Zip;
otherwise;

What is the simplest way to do this?

Thank you very much!

Upvotes: 2

Views: 76

Answers (1)

Joe
Joe

Reputation: 63434

This sounds like a vertical transpose. That would be done something like this, if all fields are character:

data want;
set have;
array fields city state zip;
do _t = 1 to dim(fields);
  if lowcase(activeColumn)=vname(fields[_t]) then activeValue=fields[_t];
  *may want an OUTPUT here.;
end;
run;

If they are mixed type you would need two arrays and loops. You might not need ActiveColumn if you are intending to just loop over all fields anyway; you can just set ActiveColumn to vname(fields[_t]) in the loop.

If you are intending to have this be more flexible, you can use array fields _character_; which will use all character variables (thus meaning you don't have to explicitly specify them).

Upvotes: 3

Related Questions