【问题标题】:SAS how to create variable with corresponding values efficientlySAS如何有效地创建具有相应值的变量
【发布时间】:2015-12-04 23:10:43
【问题描述】:

我正在尝试完成以下内容。

Variable Letter 具有三个值(a、b、c)。我想创建一个变量 Letter_2,其值对应于 Letter 的值,即 (1, 2, 3)。

我知道我可以使用三个 IF Then 语句来做到这一点。

if Letter='a' then Letter_2='1';
if Letter='b' then Letter_2='2';
if Letter='c' then Letter_2='3';

假设我有 15 个变量 Letter 的值,以及 15 个对应的替换值。有没有一种方法可以有效地做到这一点,而无需输入相同的 If Then 语句 15 次?

我是 SAS 新手。任何线索将不胜感激。

丽莎

【问题讨论】:

  • 一般来说,我已经看到这是通过查找表或从 ASCII 值中添加/减去常量来完成的。
  • 您只想找到它在列表中的位置吗?你看过WHICHC() 函数吗?但这将返回一个数字 1,2,3 而不是字符串 '1','2','3'。但是你可以使用它。
  • @Tom 实际上,我试图为变量 Letter 的值分配顺序。所以我试图创建一个包含值 Letter 的假定顺序的变量,然后使用这个新变量对数据进行排序。

标签: arrays sas


【解决方案1】:

看起来像 FORMAT 的应用程序。

首先定义格式。

proc format ;
  value $lookup 'a'='1' 'b'='2' 'c'='3' ;
run;

然后用它来重新编码你的变量。

data want;
  set have;
  letter2 = put(letter,$lookup.);
run;

或者也许您可以使用两个临时数组和WHICHC() 函数?

data have;
  input letter $10. ;
cards;
car
apple
box
;;;;

data want ;
  set have ;
  array from (3) $10 _temporary_ ('apple','box','car');
  array to (3) $10 _temporary_ ('first','second','third');
  if whichc(letter,of from(*)) then 
    letter_2 = to(whichc(letter,of from(*)))
  ;
run;

【讨论】:

  • 非常感谢。 Format 应用程序正是我在这里需要的。感谢您介绍 whichc() 函数。
猜你喜欢
  • 2018-09-03
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 2019-03-16
相关资源
最近更新 更多