Search code examples
sascharacterstoragestring-lengthcoding-efficiency

Calculating the length of a string within a variable SAS


I have imported some data into SAS through SQL. I want to change the length of the variables to improve the efficiency and storage of the dataset, however I don't know what the maximum length of the variable should be.

For example I have the variable "Forename". It's length is currently set to $300. I know this is too large but don't want to take a guess at what it should be in case I chop off any data. If I have the following names, how can I work out that I need to reset the length to $10.?:

Obs Forename    Total Character Length
1   Tim         3
2   Gary        4
3   Samantha    8
4   Christopher 10

Solution

  • This isn't really a dynamic answer but it's pretty simple. Just get the maximum length of the Forename variable.

    proc sql;
    select max(length(forename)) from have;
    quit;
    

    This will just return the max length then you can plug it into the following data step.

    data want;
    length forename $11;
    set have;
    run;