Selecting/Adressing every nth variable

Reply
Occasional Contributor
Posts: 10

Selecting/Adressing every nth variable


Hi,

I have a question concerning the selection of certain variables in a dataset:

Let's say my dataset has the variables var1, var2, ...var100. For an analysis with a certain procedure I need every fifth variable (var5, var10, var15,...).

Is there an easy way to adress these variables? I thought of building an array with dimenstion [20,5] and writing the 5th column in an array with [20]. So I can adress them as new1-new20:

array old[20,5] var1-var100

array new [20]

do i=1 to 20;

    new=old[i,5];

end;      

Is there another, better way to do this without creating new variables?

Tanks a lot for your help.

Kathrin

Respected Advisor
Posts: 3,799

Re: Selecting/Adressing every nth variable

Posted in reply to kathrin_r

I would use this technique.  I use it all the time to process variables lists.  Data V is my test data you will use YOUR data of course. Be sure to use OBS=0 data set option on the transpose when you replace V with your data set name.

data v;
   array var[100] (1:100);
   run;
proc transpose data=v(obs=0) out=varlist;
   var var:;
   run;
data varlist;
   set varlist;
   i + 1;
  
run;
proc sql;
  
select _name_ into :every5th separated by ' '
  
from varlist(where=(mod(i,5) eq 0));
   quit;
  
run;
%put NOTE: &=every5th;

Message was edited by: data _null_

Super Contributor
Posts: 1,636

Re: Selecting/Adressing every nth variable

Posted in reply to kathrin_r

maybe I missundstood your question.

data have;

input v1-v15;

cards;

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

;

data want;

set have;

array old(*) v1-v15;

array new(*) new1-new3;

do i=1 to 3;

  new(i)=old(i*5);

  end;

  drop i;

proc print;run;

   Obs  v1  v2  v3  v4  v5  v6  v7  v8  v9  v10  v11  v12  v13  v14  v15  new1  new2  new3

   1    1   2   3   4   5   6   7   8   9   10   11   12   13   14   15    5    10    15

Respected Advisor
Posts: 3,156

Re: Selecting/Adressing every nth variable

Posted in reply to kathrin_r

Or you can take advantage of some Metadata:

proc sql;

  select CATS(name) into :varname separated by ' ' from dictionary.columns

  where libname='YOURLIBNAME'/*CAPPED*/

  AND MEMNAME='YOURTABLE'/*CAPPED*/

AND MOD(VARNUM,5)=0;

QUIT;

/*

DATA WANT;

  SET YOURTABLE (KEEP=&VARNAME);

RUN;*/

All of your wanted variable names will in macro variable 'varname' , ready for use.

Haikuo

Super Contributor
Posts: 644

Re: Selecting/Adressing every nth variable

Posted in reply to kathrin_r

Another suggestion

If the variables are in the form var1 - var100 you could use a macro to define the keep list (or variables in an array)

%macro keepvar ;

     %global keepvar ;

     %do i = 5 %to 100 %by 5 ;

          %let keepvar = &keepvar var(%left(i)) ;

     %end ;

%mend ;

(untested code)

Richard

Ask a Question
Discussion stats
  • 4 replies
  • 887 views
  • 2 likes
  • 5 in conversation