SAS 基础(3) 自定义输入和输出格式

    科技2022-07-15  145

    自定义输入和输出格式

    3.1 用 informat 和 format 自定义格式3.2 用picture 照个输出模版 前期回顾: SAS 基础(2)SAS变量的输出格式 .

    3.1 用 informat 和 format 自定义格式

    基本形式:

    proc format invalue <$> 格式名 变量值或范围1 = 输出格式1 ...... ; value <$> 格式名 变量值或范围1 = 输出格式1 ...... ; picture 模板名 <数值范围>; 变量值或范围 是字符,需要在" 格式名 " 前面加$符号。<$> 是可选内容。

    例如:

    invalue $ gender 1 = “male” 2 = “female” ; 解释:创建输入格式gender,当输入 1 2时 自动变为 male ,female。male是字符要加 $

    invalue lxfmt 1-4=same 99 = . ; 解释:创建输入格式 lxfmt,当输入值为 1~ 4时,保持原有值不变,输入99变为 ‘.’ 。

    value $ grade “a”-“g”=“fair” “o”,“u” = “other” ; 解释:创建输出格式 grade,输入值介于a~g之间,输出位“fair”, o和u 输出位 other。

    value age low-<40=30 low-<50=40 50-high=50 ; 解释:创建输出格式 age 当输入值 < 40 输出为30 ,>=40 &< 50 输出为40, >50 输出 50 。

    value score low-59=“不及格” other=“及格” 解释:创建输出格式 score 输入值<=59 输出为不及格,其余输出 及格。

    . 例子:根据实际年龄按每10岁划分年龄组

    proc format; invalue fage low-<40=30 40-<50=40 50-<60=50 60-high=60; data age; input id age fage.; /* 把age 与 fage 关联起来 */ cards; 1 36 2 43 3 55 4 78 5 60 6 59 ; proc print; run;

    . 例子:输入一些固定又烦琐的文本。输入50名大学生所在的年级,分别是Freshman、Sophomore、Junior、Senior。

    proc format; invalue $grade 1="Freshman" 2="Sophomore" 3="Junior" 4="Senior" ; value fscore low-<60="不及格" 60-<80="及格" 80-high="优秀"; data Dgrade; input id Dgrade: $grade20. score; /* grade本身的宽度是1,但是 指定的输入格式是Freshman、Sophomore、Junior、Senior,他们的宽度都至少>1,因此 要预定义够大的 宽度 如grade20. */ format score fscore.; /* 把value 的fscore 关联起来与 score,注意不要把proc format与 format 混淆了。 */ cards; 1 1 60 2 4 59 3 3 80 4 2 79 ; proc print; run;

    .

    3.2 用picture 照个输出模版

    可以自己定义显示结果,例如 在数据集中的 profit 显示为 “¥” 的形式,把prop显示为 “%” 的形式 。

    proc format ; picture pft low-high = "0,000,000"(prefix="¥"); picture pro low-high = "09.990%"; /* pro的定义有0 有9,0的作用是自动舍去数字前面的0,而1-9不会舍去; 例如:0.72指定“00.00%”那会显示成“72%”,“99.99%”会显示成 00.72%, “09.99%”则显示0.72%; low-high的范围就是从最低值到最高值。 */ run; data profit; input profit prop; format profit pft. prop pro. ; cards; 29893050 16.25 36580070 21.301 ; proc print; run;

    Processed: 0.018, SQL: 8