如何查找和替换SAS数据集中的特定文本? [英] How can I find and replace specific text in a SAS data set?

查看:562
本文介绍了如何查找和替换SAS数据集中的特定文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中有400位数字的四位数代码,我想用双方的空格填充

I have a data set with 400 observations of 4 digit codes which I would like to pad with a space on both sides

ex. Dataset 
obs code
1   1111 
2   1112
3   3333
.
.
.
400 5999

我如何通过另一个大数据集,的填充400代码与。

How can I go through another large data set and replace every occurrence of any of the padded 400 codes with a " ".

ex. Large Dataset
obs text 
1   abcdef 1111 abcdef
2   abcdef 1111 abcdef 1112 8888
3   abcdef 1111 abcdef 11128888
... 

我想要的数据集

ex. New Data set
obs text
1   abcdef   abcdef
2   abcdef   abcdef   8888
3   abcdef   abcdef 11128888
...

注意:我只是希望用空格替换两边填充的4位数字。所以在obs 3中,1112将不会被替换。

Note: I'm only looking to replace 4 digit codes that are padded on both sides by a space. So in obs 3, 1112 won't be replaced.

我已经尝试执行以下proc sql语句,但它只能查找并替换第一个匹配,而不是所有的比赛。

I've tried doing the following proc sql statement, but it only finds and replaces the first match, instead of all the matches.

proc sql;  
    select   
    *,  
    tranwrd(large_dataset.text, trim(small_dataset.code), ' ') as new_text  
from large_dataset  
    left join small_dataset  
    on findw(large_dataset.text, trim(small_dataset.code))
;
quit;


推荐答案

您只需使用DO循环来扫描大数据集中每个记录的小数据集的小数据集。如果要使用 TRANWRD()函数,那么您将需要添加额外的空格字符。

You could just use a DO loop to scan through the small dataset of codes for each record in the large dataset. If you want to use TRANWRD() function then you will need to add extra space characters.

data want ;
  set have ;
  length code $4 ;
  do i=1 to nobs while (text ne ' ');
    set codes(keep=code) nobs=nobs point=i ;
    text = substr(tranwrd(' '||text,' '||code||' ',' '),2);
  end;
  drop code;
run;

DO循环将从您的CODES列表中读取记录。使用SET语句中的POINT =选项可以让您多次读取该文件。如果TEXT字符串为空,则WHILE子句将停止,因为在该点不需要继续寻找替换代码。

The DO loop will read the records from your CODES list. Using the POINT= option on the SET statement lets you read the file multiple times. The WHILE clause will stop if the TEXT string is empty since there is no need to keep looking for codes to replace at that point.

如果您的代码列表足够小并且您可以获得正确的正则表达式,那么您可以尝试使用 PRXCHANGE()函数。您可以使用SQL步骤将代码生成为可以在正则表达式中使用的列表。

If your list of codes is small enough and you can get the right regular expression then you might try using PRXCHANGE() function instead. You can use an SQL step to generate the codes as a list that you can use in the regular expression.

proc sql noprint ;
  select code into :codelist separated by '|'
  from codes
;
quit;

data want ;
  set have ;
  text=prxchange("s/\b(&codelist)\b/ /",-1,text);
run;

这篇关于如何查找和替换SAS数据集中的特定文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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