如何将字符变量中的数字转换为sas中的数字

How to convert numbers in a character variable to Numeric in sas

谁能帮我解决这个问题?

我有一个非常大的原始数据集,它有一个字符变量,其中包含文本字符串以及以字符格式定义的数字和日期。现在我想处理数据集并创建一个新的数值变量,并且仅当实际变量中的文本是数字或日期值时才填充值。否则缺失

原始数据:

ACTUAL_VARIABLE                              NEW_NUM_VARIABLE(Expected Values)
------------------                           ---------------------------------
ODed on pills threw them all up - 2006
Y
1                                                        1
5                                                        5
ODed on pills
6                                                        6
Less than once a week
N
N
2006-11-12                                               2006-11-12

非常感谢

最简单的方法(如果您知道具体的日期格式)是使用输入功能。 09:27 如果 put(input(var,??yymmdd10.),yymmdd10.)=var 那么它是一个日期!

else if input(var,best.) ne . then its a number.

Otherwiseits a character string.

这并不像乍看起来那么简单,所以我明白为什么很难找到答案。只是提取一个数字非常容易,但是当包含日期时,它会变得有点复杂(特别是当输入的格式可能发生变化时,例如 yyyy-mm-dd、dd-mm-yyyy、dd/mm/yy 等)。

首先要注意一点。如果您想将新值存储为数字字段,则不能混合显示数字和日期。日期存储为数字并设置格式以显示日期,但您不能在行级别应用格式。因此我建议创建 2 个新列,1 个用于数字,1 个用于日期。

我的首选方法是使用 anyalpha 函数排除任何带有字母字符的记录,然后使用 anypunct 函数来识别标点符号是否存在(这应该识别日期而不是只是数字)。 anydtdte 信息格式然后用于提取日期,这是一个非常有用的信息格式,因为它读取以不同方式存储的日期(根据我上面的注释)。

此方法显然有一些注意事项。

  • 如果任何数字包含小数,那么我的方法会错误地将它们视为日期,因此只会正确分配整数。
  • 它不会选择包含月份的日期作为单词,例如2015 年 5 月 15 日,因为 anyalpha 函数会将它们排除在外。它们将只需要包含数字,由任何标点符号分隔。

这是我的代码。

/* create initial dataset */
data have;
input actual_variable $ 50.;
datalines;
ODed on pills threw them all up - 2006
Y
1                                       
5                                       
ODed on pills
6                                       
Less than once a week
N
N
2006-11-12                              
;
run;

/* extract dates and numbers */
data want;
set have;
if not anyalpha(actual_variable) then do; /* exclude records with an alphabetic character */
    if anypunct(actual_variable) then new_date_variable = input(actual_variable,anydtdte10.); /* if a punctuation character exists then read in as a date */
    else new_num_variable = input(actual_variable,best12.); /* else read in as a number */
end;
format new_date_variable yymmdd10.; /* show date field in required format */
run;