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

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

问题描述

我有一个数据集,其中包含 400 个 4 位代码的观察值,我想在两侧用空格填充

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/(&codelist)/ /",-1,text);
run;

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

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