DATA Step, Macro, Functions and more

Referencing SAS Columns by location not variable name

Accepted Solution Solved
Reply
Contributor
Posts: 53
Accepted Solution

Referencing SAS Columns by location not variable name

Is there a way to reference a column by position rather then its variable name.  I have multiple variables that have different names but i want to loop through them. 

I have searched quite a bit for this but must be using the wrong terminology because i cant seem to get close to the answer I am looking for.  Is my only option to create an array and

name out all the variables and then step through the array?  Or is there a way to just pick variables 5 - 15 and loop through them.

Thanks


Accepted Solutions
Solution
‎05-02-2014 03:32 PM
Super Contributor
Posts: 1,636

Re: Referencing SAS Columns by location not variable name

It might worth the trouble creating a macro if you have a lot of files.

Sample code:

%let dsn=sashelp.class;

proc contents data=&dsn noprint out=test(keep=name varnum);

data _null_;

  set test(where=(varnum in(3,5)));;

  call symputx(cats('var',varnum),name);

run;

data want;

   set &dsn;

   array _abc(*) &var3--&var5;

   array _new(*) new3-new5;

   do _n_=1 to dim(_abc);

   _new(_n_)=_abc(_n_)*100;

   end;

proc print;run;

Message was edited by: Linlin

View solution in original post


All Replies
Super User
Posts: 19,768

Re: Referencing SAS Columns by location not variable name

I think you need to list them out in an array.

If its a one-off then that's the easiest. If its done multiple times, you could query sashelp.vcolumns and create a macro variable out of the names to feed an array but that seems like more work to me.

Depending on what you're doing IML may also be an option.

Solution
‎05-02-2014 03:32 PM
Super Contributor
Posts: 1,636

Re: Referencing SAS Columns by location not variable name

It might worth the trouble creating a macro if you have a lot of files.

Sample code:

%let dsn=sashelp.class;

proc contents data=&dsn noprint out=test(keep=name varnum);

data _null_;

  set test(where=(varnum in(3,5)));;

  call symputx(cats('var',varnum),name);

run;

data want;

   set &dsn;

   array _abc(*) &var3--&var5;

   array _new(*) new3-new5;

   do _n_=1 to dim(_abc);

   _new(_n_)=_abc(_n_)*100;

   end;

proc print;run;

Message was edited by: Linlin

Super User
Posts: 11,338

Re: Referencing SAS Columns by location not variable name

You don't say what you are going to do with a loop but you would likely want to make sure that the variables are the same type for many operations.

Something else to look at might be the Open, Varnum and Varname functions for reading details about datasets but I would likely start with the Dictionary tables i.e. Reeza's sashelp.vcolumns

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 233 views
  • 6 likes
  • 4 in conversation