使用 case-when 或 proc import 更改 SAS 中变量的格式

问题描述 投票:0回答:1

我有多个使用 PROC IMPORT 从 txt 文件导入的表。我想 rbind 连接在一起,但某些列格式不匹配。

表1:

ID(号码) 代码(数字) 描述(字符) 邮编(编号)
01 8 描述1 91023
02 10 描述2 60603

表2:

ID(字符) 代码(数字) 描述(字符) zip(字符)
A1 10 描述2 未知
A2 15 描述3 未知

表3:

ID(号码) 代码(数字) 描述(字符) zip(字符)
80 20 描述2 未知
83 16 描述3 未知

最终输出:

ID(字符) 代码(数字) 描述(字符) zip(字符)
01 8 描述1 91023
02 10 描述2 60603
A1 10 描述2 未知
A2 15 描述3 未知
80 20 描述2 未知
83 16 描述3 未知

有超过 3 个表格,并且有多个列格式不匹配。我对每列想要什么格式有一个想法(在本示例中,我希望格式类似于表 3)。

我的目标是创建一个宏函数,对于每个表,我可以看到变量类型是什么,然后根据我是否需要列是字符还是数字,使用 case when 语句将列更改为正确的列格式。 我首先尝试获取 vtype,然后使用 case-when 语句。

   data table1_type;
    set table1;
       id_var = vtype(ID); /*want the final col to be char*/
       code_var = vtype(code);  /*want the final col to be num*/
       descr_var = vtype(descr);  /*want the final col to be char*/
       zip_var = vtype(zip);  /*want the final col to be char*/
    run;

 proc sql;
    create table table1_format as 
    select * ,
       case when id_var = "N" then put(id, 4.) else ID end as ID_reformat 
/*If the ID is numeric then I want it converted into a character, but if it's a character then I want it to output still as a character*/
    from table1_type;
    quit;

但是我收到此错误:WHEN 子句 2 的结果与前面的结果的数据类型不同。

我不确定这是否是尝试解决此问题的最佳方法。有人有更好的办法吗?谢谢你。

编辑: 我的 PROC IMPORT 语句如下所示:

PROC IMPORT OUT= WORK.table1
DATAFILE= "filelocation/table1.txt"
DBMS=DLM REPLACE;
DELIMITER='|';
guessingrows = max;
RUN;
sql database sas
1个回答
0
投票

最简单的解决方案是首先一致地读取文件。

让我们创建两个类似于前两个示例的文本文件,以便我们可以使用它们进行编码。

options parmcards=file1;
filename file1 temp;
parmcards;
ID (num),CODE (num),Descr (char),zip (num)
01,8,Desc 1,91023
02,10,Descr 2,60603
;

options parmcards=file2;
filename file2 temp;
parmcards;
ID (char),CODE (num),Descr (char),zip (char)
A1,10,Desc 2,Unknown
A2,15,Descr 3,Unknown
;

现在让我们使用完全相同的代码来读取它们,以便我们获得具有以完全相同的方式定义的相同变量的数据集。

data file1;
  infile file1 dsd truncover firstobs=2 ;
  input ID :$10. CODE DESCR :$30. ZIP :$9. ;
run;

data file2;
  infile file2 dsd truncover firstobs=2 ;
  input ID :$10. CODE DESCR :$30. ZIP :$9. ;
run;

现在我们可以轻松地将数据集组合在一起。

data want;
  set file1 file2;
run;

结果

OBS    ID    CODE     DESCR       ZIP

 1     01      8     Desc 1     91023
 2     02     10     Descr 2    60603
 3     A1     10     Desc 2     Unknown
 4     A2     15     Descr 3    Unknown
© www.soinside.com 2019 - 2024. All rights reserved.