sas

Convert the (character) variable values


Suppose I have values of a variable that looks like this:

2015-W01
2015-W02
2015-W03
.....

How can I convert them in the following?:

1w2015
2w2015
3w2015
.....

Solution

  • You can do this by using scan to find strings that you need, then concatenate them with cats in the order that you need.

    data want;
        set have;
        str  = '2015-W01';
        str2 = cats(input(scan(str, 2, 'W'), 8.), 'w', scan(str, 1, '-'));
    run;
    
    str         str2
    2015-W01    1w2015
    

    Let's break it down.

    1. Getting the week number first

    You want the week number first without a leading zero. Let's consider W to be the separator of out string. We'll get the second word separated by W, which is 01

    scan(str, 2, 'W')
    

    But, this still gives a leading zero. We'll convert it into a number which automatically removes the leading zero.

    input(scan(str, 2, 'W'), 8.)
    

    Let's move onto the next part: concatenating. cats will automatically convert the number into a string for us, so we don't need to worry about doing a second conversion.

    2. Concatenation

    Just add w:

    cats(input(scan(str, 2, 'W'), 8.), 'w')
    

    This gets us the string:

    1w

    Now we just need to get the year.

    3. Add the year

    We'll now look at the whole string again just like we did in part 1, but as a - separated string. The first word in that string is the number, so we'll get that.

    scan(str, 1, '-')
    

    4. Putting it all together

    For our final code, we get this:

    cats(input(scan(str, 2, 'W'), 8.), 'w', scan(str, 1, '-'));