SAS Proc Format – 根据子串格式化字符

huangapple go评论61阅读模式
英文:

SAS Proc Format - Format a character based on a substring

问题

I want to know if it is possible to create a custom format that will work on a range of character values by taking a substring and formatting it base on that.

e.g. A001, B001, C001 are all formatted to 'JAN'
A002, B002, C002 are all formatted to 'FEB'

Is this possible?

'A002', 'B002', 'C002' = 'FEB';
etc.

I know you can just list specific character values you want formatted (as above), but I would like this to work for any letter at the beginning and only read the last 3 characters to determine the format, without having to list all possible iterations.

英文:

I want to know if it is possible to create a custom format that will work on a range of character values by taking a substring and formatting it base on that.

e.g. A001, B001, C001 are all formatted to 'JAN'
A002, B002, C002 are all formatted to 'FEB'

Is this possible?

value $custom_format'A001', 'B001', 'C001' = 'JAN'
'A002', 'B002', 'C002' = 'FEB';
etc.

I know you can just list specific character values you want formatted (as above), but I would like this to work for any letter at the begining and only read the last 3 characters to determin the format, without having to list all possible iterations.

答案1

得分: 0

Use substr 只提取最后 3 个值并基于此创建格式。

proc format;
    value $custom_format
        '001' = 'JAN'
        '002' = 'FEB'
    ;
run;

/* substr(var, 2) 将从第二个字符开始读取,直到结束 */
data test;
    var = 'A001';
    month = put(substr(var, 2), $custom_format.);
    output;

    var = 'B002';
    month = put(substr(var, 2), $custom_format.);
    output;
run;

输出:

var	    month
A001	JAN
B002	FEB

如果需要更复杂的内容,可以在 SAS 中向格式提供正则表达式。

英文:

Use substr to only pull the last 3 values and create a format based on that.

proc format;
    value $custom_format
        '001' = 'JAN'
        '002' = 'FEB'
    ;
run;

/* substr(var, 2) will start at the second character and read until the end */
data test;
    var = 'A001';
    month = put(substr(var, 2), $custom_format.);
    output;

    var = 'B002';
    month = put(substr(var, 2), $custom_format.);
    output;
run;

Output:

var	    month
A001	JAN
B002	FEB

If you need something more complex, you can supply regex to formats in SAS.

huangapple
  • 本文由 发表于 2023年2月8日 17:59:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定