SAS:将字符转换为数字而不创建另一个变量 [英] SAS : Convert character to numeric without creating another variable

查看:31
本文介绍了SAS:将字符转换为数字而不创建另一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 x 转换为数字.

I want to convert x to numeric.

DATA test;
  input x $1.;
  cards;
  1
  2
  0
  ;
run;

我尝试了不同的方法:

  • 使用 *1 :

/* trial1 */
DATA test1;
  SET test;
  x = x*1;
run;

日志打印以下注释:

NOTE: Character values have been converted to numeric values at the places given by: (Line):(Column).
      2470:3
NOTE: Numeric values have been converted to character values at the places given by: (Line):(Column).
      2470:4

而且格式没有改变.

  • 使用 input() :

/* trial2 */
DATA test2;
  SET test;
  x = input(x,BEST1.);
run;`

日志打印以下注释:

NOTE: Numeric values have been converted to character values at the places given by: (Line):(Column).
  2396:3

而且格式没有改变.

  • 使用 informat :

/* trial3 */
DATA test3;
  SET test;
  informat x BEST1.;
run;

日志打印以下错误:

ERROR 48-59: The informat $BEST was not found or could not be loaded.

此处here :编译器检测变量和格式的不同类型,假设这是一个错误,添加假定缺失的$,因此找不到格式.

Which is explained here and here : the compiler detects different types for variable and format, assumes it's a mistake, add the presumed-missing $ and therefore doesn't find the format.

如果我创建了第二个变量,例如:

All these trials would work if I created a second variable like for example :

DATA test4;
  SET test (rename=(x=x2));
  x = x2*1;
  drop x2;
run;

但我正在尝试清理我的代码,我想知道是否有办法在不这样做的情况下进行这样的转换?

But I'm trying to clean up my code and I wonder if there is a way to do such a conversion without doing so ?

推荐答案

如别处所述,您确实需要使用第二个变量.SAS 不会让您直接更改列的变量类型,但您可以通过与上述类似的方式使用 rename 来作弊.

As noted elsewhere, you do need to use a second variable. SAS won't let you alter the variable type of a column directly, but you can cheat things by using rename in a similar way as above.

我要建议的与 NEOmen 的答案或您上面的答案不同的一件事是使用 input.长度/赋值或使用 *1 方法都很好,但它们依赖于 SAS 的自动类型转换,它会在您的日志中添加一条说明它正在执行此操作.你应该避免在你的日志中出现这样的事情,因为它们很乱,让别人认为你可能是无意中做的.

The one thing I'm going to suggest different from NEOmen's answer or yours above is using input. Length/assignment or using the *1 method are both fine, but they rely on SAS's automatic type conversion, which will add a note to your log that it's doing it. You should avoid things like that in your log, as they are messy and make others think you may have done it on accident.

使用 NEOmen 的测试数据集:

Using NEOmen's test dataset:

data test1;
  set test(rename=x=x_old);
  x=input(x_old,best12.); *whatever is appropriate informat for your variable;
run;

这篇关于SAS:将字符转换为数字而不创建另一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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