SAS中的虚拟变量

SAS中的虚拟变量,sas,Sas,假设我们有一些数据集people,其中有一个分类变量income,有4个级别(1,2,3,4)。我们将如何在SAS中编写此代码?是不是: data people; set people; if income=1 then income1=1; else if income=2 then income2=1 else if income =3 then income3=1; run; 换句话说,这将为四个级别创建三个虚拟变量。是这样吗?我已经修改了下面的代码。这将给出3个虚拟编码变量收入=4将

假设我们有一些数据集
people
,其中有一个分类变量
income
,有4个级别(1,2,3,4)。我们将如何在SAS中编写此代码?是不是:

data people;
set people;
if income=1 then income1=1;
else if income=2 then income2=1
else if income  =3 then income3=1;
run;

换句话说,这将为四个级别创建三个虚拟变量。是这样吗?

我已经修改了下面的代码。这将给出3个虚拟编码变量<代码>收入=4将是您的参考代码

data people_dummy;
         set people;
         if income=1 then income1=1 ; else income1=0;
         if income=2 then income2=1 ; else income2=0; 
         if income=3 then income3=1 ; else income3=0;
run;

更灵活的方法是使用数组

data people;
set people;
array incomes income1-income4;
do _t = 1 to dim(incomes);
  if income=_t then income[_t] = 1;
  else if not missing(income) then income[_t]=0;
  else income[_t]=.;
end;
run;

我会写一些更一般的东西

%macro cat(indata, variable);
  proc sql noprint;
    select distinct &variable. into :mvals separated by '|'
    from &indata.;

    %let mdim=&sqlobs;
  quit;

  data &indata.;
    set &indata.;
    %do _i=1 %to &mdim.;
      %let _v = %scan(&mvals., &_i., |);
      if &variable. = &_v. then &variable.&_v. = 1; else &variable.&_v = 0;
    %end;
  run;
%mend;

%cat(people, income);
你不必写“其他”。以下内容也将起作用:

    income1_ind=(income1 eq 1);
    income2_ind=(income2 eq 2);
代码:-

proc sql noprint;
 select distinct 'income' || strip(put(income,8.)) into :income_var    separated by ' '
 from people;
quit;

data people(rename = (in = income));
 set people(rename = (income = in));
 length &income_var. 8;
 array tmp_arr(*) income:;
 do i = 1 to dim(tmp_arr);
    if in eq i then tmp_arr(i) = 1;
    else tmp_arr(i) = 0;
 end;
 drop i;
run;
工作:上述SAS代码是动态的,适用于任何级别的收入变量,因为它根据输入人员数据集中不同级别的数量自动创建变量数量


数据步骤将根据收入变量的值将相应变量设置为值1,将其他变量设置为0。

您必须在else语句前的行后添加分号。