BigDulles
BigDulles

Reputation: 31

SAS Change values of Variables without 3 Data Steps

Often when I am coding in SAS, I need to change values of variables, like turning a character into a numeric, or rounding values. Because of how SAS works as far as I know, I often have to do it in three steps, like so:

data change;
    set raw;
    words = put(zipcode, $5.);
run;

data drop;
    set change;
    drop zipcode;
run;

data rename;
    set drop;
    rename words = "zipcode";
run;

Is there a way to do something like this in a single data or proc step, rather than having to type out three? And not just for a variable type conversion, but for things like the ROUND statement as well.

Thanks in advance.

Upvotes: 3

Views: 341

Answers (2)

Tom
Tom

Reputation: 51566

There is no need to do that in three steps. One step is enough.

data rename;
    set raw;
    words = put(zipcode, $5.);
    drop zipcode;
    rename words = zipcode;
run;

Upvotes: 0

Stu Sztukowski
Stu Sztukowski

Reputation: 12899

This is where dataset options are a huge advantage. They work in the DATA Step, SQL, and almost every PROC where a dataset is referenced.

You can do all of this in a single data step multiple ways.

1. An output dataset option

data change(rename=(words = zipcode) );
    set raw;
    words = put(zipcode, $5.);

    drop zipcode;
run;

Here's what's happening:

  1. words is created in the dataset
  2. At the end of the data step, zipcode is dropped.
  3. As the very last step after zipcode is dropped, words is renamed to zipcode

This is called an output dataset option. It's the last thing that happens before the dataset is finally written.

2. An input dataset option

data change;
    set raw(rename=(zipcode = _zipcode) );
    words = put(_zipcode, $5.);

    drop _zipcode;
run;

Here's what's happening:

  1. Before raw is read, zipcode is renamed to _zipcode
  2. words is created
  3. _zipcode is dropped from the dataset

Input/output dataset options are very powerful. You can create special where clauses, indices, compress data, and much more using them.

You can view all of the available dataset options here: https://go.documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/ledsoptsref/p1pczmnhbq4axpn1l15s9mk6mobp.htm

Upvotes: 2

Related Questions