DATA Step, Macro, Functions and more

How to add sequence prefix to hundreds of variables?

Reply
Contributor
Posts: 20

How to add sequence prefix to hundreds of variables?

Dear All,

 

I would like to add sequence prefix to a group of variables. In my current data, my variables' names are all in the format of "_"+XXXX (four random number), for example, they are like _3452, _8342, etc. I would like to add a sequence prefix to each of my variables' name, like change them to val1_3452, val2_8342,...,.

 

Appreciate any advice!

 

Thank you.

 

Super User
Posts: 23,999

Re: How to add sequence prefix to hundreds of variables?

[ Edited ]

Do you really have to?

You can use the -- to create a list of variables that are listed in order in the data set.

 

You can use the approach I mentioned without doing any of this - you can list the variables in an array for one. If you want to use the Call Execute solution, again, list the array and then use VNAME to pull the variable name to push to the call execute statement, which is the solution you marked as correct in your previous question. 

 

data example;
set have (obs=1);

array _var_list (*) first_variable -- last_variable;

do i=1 to dim(_var_list);

name = vname(_var_list(i));

*add the call execute here with the variable name now;
output; end; run;

 

 

Super User
Posts: 23,999

Re: How to add sequence prefix to hundreds of variables?

And if you really, really, really do want to do that, see this solution here, which does it for suffixes but can be adapted for prefixes as well:

 

https://gist.github.com/statgeek/82d9f2854edc01560e0f

Super User
Posts: 6,933

Re: How to add sequence prefix to hundreds of variables?

[ Edited ]

I'm not sure I see the value gained by doing this, but a reasonably short program can do this:

 

proc contents data=have noprint out=names (keep=name);

run;

 

data newnames;

set names;

newname = cats('val', _n_, name);

where name =: '_';

run;

 

proc sql noprint;

select trim(name) || '=' || newname into : rename_list separated by ' ' from newnames;

quit;

 

data want;

set have;

rename &rename_list;

run;

 

This is untested but looks about right.

Contributor
Posts: 54

Re: How to add sequence prefix to hundreds of variables?

You can use _n_ and concatanate it with variabli.
Data new;
Set old;
X=_n_;
Y="var"||X||"_"||my_variable;
Run;

You can also use catx,
Ask a Question
Discussion stats
  • 4 replies
  • 433 views
  • 0 likes
  • 4 in conversation