SAS 替换所有列中的字符 [英] SAS replace character in ALL columns

查看:82
本文介绍了SAS 替换所有列中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SAS 数据集,我必须将其导出为 .csv 文件.我有以下两个相互矛盾的要求.

I have a SAS dataset that I have to export to a .csv-file. I have the following two contradicting requirements.

  • 我必须使用 分号 作为 .csv 文件中的分隔符.

  • I have to use the semicolon as the delimiter in the .csv-file.

某些字符变量是从公式中手动输入的字符串,因此它们可能包含分号.

Some of the character variables are manually inputted strings from formulas, hence they may contain semicolons.

我对上述问题的解决方案是转义分号或用逗号替换它.

My solution to the above is to either escape the semicolon or to replace it with a comma.

我的尝试:

对于每个变量,对数据集中的变量使用 tranwrd(.., ";", ",") 函数.更新数据集并遍历所有变量.然而,对于即使是半大型数据集,这自然是一种非常效率低下的方法,因为我必须为每个变量做一个数据步骤.它的代码非常难看,因为我必须通过几步来获取变量名,但效率低下肯定会占上风.

For each variable, use the tranwrd(.., ";", ",") function on a variable in the data set. Update the dataset and loop through all variables. This, however, is naturally a very inefficient way of doing it for even semi-large datasets, since I have to do a datastep for each variable. The code for it is quite ugly, since I have to get the variable names by a few steps, but the inefficiency definitely takes the cake.

data test;
    input w $ c b  d  e $ f $;
    datalines4;
Aaa;; 50 11 1 222 a;s                                        
Bbb 35 12 2 250 qw                                        
Comma, 75 13 3 foo zx                                        
;;;;
run;

* Get the variable names;
proc contents data=test out=vars(keep=name type varnum) order=varnum noprint;
run;
* Sort by variable number;
proc sort data=vars;
    by varnum;
run;

* Put variable names into a space-separated string;
proc sql noprint;
    select compress(name)        
    into :name_list separated by ' '                      
    from vars;
quit;

%let len = %sysfunc(countw(&name_list));


*Initialize loop dataset;
data a;
    set test;
run;

%macro loop;
    %do i = 1 %to &len;
        %let j = %scan(&name_list,&i);

        data a(rename=(v_&j = &j) drop=&j);
            set a;
            v_&j.=compress(tranwrd(&j,";",","));
        run;
    %end;
%mend;
%loop;

推荐答案

我想我可能有更优雅的解决方案:

I think I may have more elegant solution to your problem:

data class;
   set sashelp.class;

   array vars [*] _character_;

   do i = 1 to dim(vars);
      vars[i] = compress(tranwrd(vars[i],"a","X"));
   end;

   drop i;
run;

您可以使用 array 来引用数据集中的所有字符列,然后遍历它们.

You can use array to reference all character columns from your data set and then loop through them.

这篇关于SAS 替换所有列中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆