Patrick Balada
Patrick Balada

Reputation: 1450

How can I set the variable labels in SAS using a table?

Suppose I am given a dataset (Table 1) with the following column names:

X1, X2, ... , XN

I have a second file (Table 2) containing the description of the variables. It look as follows:

Var  Description
X1   Description of X1
X2   Description of X2
.    ...
.    ...
.    ...
XN   Description of XN

How could I label Table 1 using Table 2?

Upvotes: 1

Views: 755

Answers (1)

Joe
Joe

Reputation: 63424

It's a little more complicated to do this in SAS than it is in R or similar; there's not a simple one-step solution. But with some basic knowledge of macro language, it's not particularly complicated.

First, you need a macro that takes a variable name and a string as parameters.

%macro label_it (var=, label=);
  label  &var. = "&label.";
%mend label_it;

Then you need to generate a list of macro calls. Assuming you have a dataset varlabels with variables var and description:

proc sql;
  select cats('%label_it(var=',var,',label=',description,')')
    into :labellist separated by ' '
    from varlabels;
quit;

Then you just use that new macro variable &labellist. in whatever context you prefer - data step or PROC DATASETS.

data want;
  set have;
  &labellist.;
run;

or

proc datasets lib=work;
  modify have;
  &labellist.;
run; quit;

There are lots of other ways to do this, but this is probably the simplest. It's possible to do this in more-or-less one step, but it's a lot more complicated and probably slower rather than faster (using DOSUBL).

Upvotes: 2

Related Questions