我有一个字符变量,它包含仅包含字符的值、仅包含数字的值以及包含数字和字母字符组合的其他值。我在下面列出了一小部分潜在变量值。
1811
1826
1st airport
1000 islands
1111
: Heathrow
9928
: Seattle
AC2277
我正在尝试将仅包含数字的值重新编码为“NA”(即 obs 1、2、5、7),我想知道是否有人知道如何做到这一点?我正在使用的数据集非常大(数以百万计的观察值),因此根据 proc freq 输出手动重新编码这个变量可能非常详尽。
如果您有任何解决此问题的提示,我们将不胜感激!
我不知道有任何数据步骤可以执行此请求。我不想使用以数字开头或以数字结尾的语句,因为中间字符可能包含字母字符。
您可以使用正则表达式执行此操作,但使用
input
函数更容易。我们将使用 input
通过检查它是否遵循 w.
信息来尝试将字符串转换为数字。如果它返回一个非缺失值,那么我们就知道它是一个数字。如果是数字,我们将用NA
替换字符串。
资料:
data have;
input string$15.;
datalines;
1811
1826
1st airport
1000 islands
1111
: Heathrow
9928
: Seattle
AC2277
;
run;
代码:
data want;
set have;
if(input(string, 8.) NE .) then string = 'NA';
run;
输出:
string
NA
NA
1st airport
1000 islands
NA
: Heathrow
NA
: Seattle
AC2277
除了Stu的回答,还可以使用regex和notdigit函数。
data want;
set have;
* notidigit() > 0 if anything other than digit is found;
if not notdigit(strip(string)) then notdigit = 'NA';
* use regex to determine if entire string is digit(s);
if prxmatch('/^[\d]+$/', strip(string)) then regex = 'NA';
run;
string notdigit regex
1811 NA NA
1826 NA NA
1st airport
1000 islands
1111 NA NA
: Heathrow
9928 NA NA
: Seattle
AC2277
我们知道,
compress
可以去除特定字符。修饰符“d
”将去除字符串中的所有数字。反过来想,如果用字母“d”压缩的字符串为空,则表示它是一个仅包含数字的字符串。
data have;
input string$15.;
datalines;
1811
1826
1st airport
1000 islands
1111
: Heathrow
9928
: Seattle
AC2277
;
run;
代码:
data want;
set have;
if compress(string,,"d") = "" then string="NA";
run;
如果你有小数或负数,使用
compress(string,".-","d")
会有所帮助。