Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad out character fields in SAS?

Tags:

sas

I am creating a SAS dataset from a database that includes a VARCHAR(5) key field.

This field includes some entries that use all 5 characters and some that use fewer.

When I import this data, I would prefer to pad all the shorter entries out to use all five characters. For this example, I want to pad on the left with 0, the character zero. So, 114 would become 00114, ABCD would become 0ABCD, and EA222 would stay as it is.

I've attempted this with a simple data statement, but of course the following does not work:

data test;
    set databaseinput;
    format key $5.;
run;

I've tried to do this with a user-defined informat, but I don't think it's possible to specify the ranges correctly on character fields, per this SAS KB answer. Plus, I'm fairly sure proc format won't let me define the result dynamically in terms of the incoming variable.

I'm sure there's an obvious solution here, but I'm just missing it.

like image 459
purple_arrows Avatar asked Nov 07 '11 16:11

purple_arrows


2 Answers

Here is an alternative:

data padded_data_dsn; length key $5;
    drop raw_data;
    set raw_data_dsn(rename=(key=raw_data));
    key = translate(right(raw_data),'0',' ');
run;
like image 164
ChrisP Avatar answered Sep 19 '22 15:09

ChrisP


Data raw_data_dsn;
format key $5.;
key = '4'; key1 = CATT(REPEAT('0',5-length(key)),key);output;
key = 'A114'; key1 = CATT(REPEAT('0',5-length(key)),key);output;
key = 'A1140'; key1 = CATT(REPEAT('0',5-length(key)),key);output;
run;
like image 23
Venkateshwaran Avatar answered Sep 18 '22 15:09

Venkateshwaran