Transposing wide to long with an array in SAS

2019-03-03 02:02发布

问题:

I have a SAS dataset, with the following variables: ID, Var1_0, Var1_3, Var1_6, Var2_0, Var2_3, Var2_6, which can be read like this: Var1_0 is parameter 1 at time 0. For every subjects I have 2 variables and 3 time points. I want to transpose this into a long format using an array, I did this:

data long;
    set wide;
    array a Var1_0 Var1_3 Var1_6 Var2_0 Var_3 Var_6;
    Do i=1 to dim(a);
        outcome = a[i];
        *Var = ???;
        if (mod(i,3)=1) then Time = 0;
            else if (mod(i,3)=2) then Time = 3;
                else Time = 6;
        Output;
    end;
    keep ID Outcome Time;
run;

The problem is that I don't know how to calculate the parameter variable, i.e., I want to add a variables that is either 1 or 2, depending on which parameter the value is related to. Is there a better way of doing this? Thank you !

回答1:

Reeza gave you the answer in her comment. Here it is typed out.

data long;
   set wide;
   array a[*] Var1_0 Var1_3 Var1_6 Var2_0 Var2_3 Var2_6;
   do i=1 to dim(a);
      outcome = a[i];
      var = vname(a[i]);
      time = input(scan(var,2,'_'),best.);
      /*Other stuff you want to do*/
      output;
   end;
run;

VNAME(array[sub]) gives you the variable name of the variable referenced by array[sub].

scan(str,i,delim) gives you the ith word in str using the specified delimiter.



标签: sas