Example : Renaming/Delete part of a label of a SAS variable in the dataset

Scenario : I got a dataset with variables RESULTS00-RESULTS36, each with a label with something like 'Result blabla'. Now I want to remove the 'Result' from the label so it will be 'blabla' alone.

Explanation: Here the user got a dataset with 37 variables naming RESULTS00 to RESUTLS36. These variables are labeled something like "RESULT ***Some String***".

Now user wants to modify the labels and remove the string "RESULT" from the label.

Solution: This can be done using simple data step and label statement. Where the new label for a variable will overwrite the older one. But this way has got two drawbacks

  • As the number of variables are large need to type in all the 37 label statements and remember the all the labels.

  • Need to iterate through all the observations of the dataset unnecessarily.

To overcome this we can take the following way;

  • Create macro which will generate the label statement automatically and thereby saving programmers efforts.

  • Use PROC DATASETS instead of DATA STEP. It is more optimistic way when we need to alter the metadata instead of changing the actual data in dataset.

This way has been demonstrated in code below;

SAS Code

assign_label;

%assign_label;

%end;

call symput('lbl_str', str);

run;

%mend;

"LABEL RESULTS&i = RESULTS &i;"; %end;

/* creating a sample dataset with 37 variables for demo */

data temp;

input RESULTS00-RESULTS36;

cards;

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

run;

/* creating a global macro variable */

%global lbl_str;

options symbolgen;

/* Macro to generate label statement which will be used to assign the labels in PROC DATASET */

%macro assign_label;

data _null_;

length str $ 1500;

%do i=0 %to 36; %if &i lt 10 %then %do;

str = trim(left(str)) || "LABEL RESULTS0&i = RESULTS0&i;";

%end;

%else %do;

str = trim(left(str)) ||

%end;

call symput('lbl_str', str);

run;

%mend modify_label;

%modify_label;

proc datasets lib=work;

modify temp;

&lbl_str;

quit;

proc contents data = work.temp NODETAILS;

run;

"LABEL RESULTS&i =" || trim(left(TRANWRD(vlbl,"RESULTS", "")))|| ";" ; %end;

vlbl = trim(left(VLABEL(RESULTS&i)));

str = trim(left(str)) ||

"LABEL RESULTS0&i =" || trim(left(TRANWRD(vlbl,"RESULTS", ""))) || ";" ; %end; %else %do;

/* Assigning Labels to variables using PROC DATASET */

proc datasets lib=work;

modify temp;

&lbl_str;

quit;

proc contents data = work.temp NODETAILS;

run;

%macro modify_label;

data _null_;

set temp (obs=1);

length str $ 1500;

%do i=0 %to 36; %if &i lt 10 %then %do;

vlbl = trim(left(VLABEL(RESULTS0&i)));

str = trim(left(str)) ||

Output of the Code:

Proc Contents Before changing the labels

PROC Contents output after changing the labels: