sas - Convert the (character) variable values - Stack Overflow

suppose to have values of a variable that looks like this:2015-W012015-W022015-W03.....how can I con

suppose to 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
.....

Thank you in advance

suppose to 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
.....

Thank you in advance

Share Improve this question asked Mar 11 at 17:35 NewUsr_statNewUsr_stat 2,5835 gold badges29 silver badges41 bronze badges 1
  • Do you really want '1w2015'? That will cause weeks 11 to 19 to sort before week 2. – Tom Commented Mar 11 at 18:50
Add a comment  | 

1 Answer 1

Reset to default 1

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, '-'));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744779241a4593232.html

相关推荐

  • sas - Convert the (character) variable values - Stack Overflow

    suppose to have values of a variable that looks like this:2015-W012015-W022015-W03.....how can I con

    2天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信