Issue with arrays for creating new variables

Reply
Occasional Contributor
Posts: 7

Issue with arrays for creating new variables

I have a 12-characters variable sales in the form of, say, "YYYNNNYNYYYN". I am using array to create 12 new variables with one character each. When I use array with substring, I am getting not only 12 variables but also 12 new rows for each observation. So, if I had 50 observations, I am now getting 12*50=600 observations, along with the 12 newly created variables. I am not able to figure out why this is happening.

 

The syntax I am using is:

 

array x[12] month1-month12;

do i=1 to 12;

     x[i]=substr(sales, i, 1);

     output;

end; 

drop i;

run;

 

Thank you!

Super User
Posts: 19,815

Re: Issue with arrays for creating new variables

array x[12] month1-month12;
do i=1 to 12;
     x[i]=substr(sales, i, 1);
     output;
end; 
drop i;
run;

OUTPUT is within the loop. Move it to outside of the loop, so it outputs at the END of the process. Now it outputs every record*month so you get N*12 records in total. FYI- you can use the CHAR or Substr() to loop this, I find the CHAR function more useful. 

 

Another option - if you read this file from a CSV or other dataset you may be able to modify the input to read all the records initially.

Super User
Posts: 5,511

Re: Issue with arrays for creating new variables

Get rid of the OUTPUT statement to get rid of the extra observations.

 

Also note, you may be creating your new variables as numeric instead of character.  If the new variables are not already defined earlier in your program, change the array statement:

 

array x[12] $ 1 month1-month12;

Respected Advisor
Posts: 3,156

Re: Issue with arrays for creating new variables

Ok, this is just for fun Smiley Happy,

 

data test;
sales='YYYNNNYNYYYN';
array x[12] $ 1 month1-month12;
call pokelong(sales,addrlong(x(1)),dim(x));
run;
Valued Guide
Posts: 2,177

Re: Issue with arrays for creating new variables

Reads like P. Dorfman code :-)
Respected Advisor
Posts: 3,156

Re: Issue with arrays for creating new variables

Indeed!

Occasional Contributor
Posts: 7

Re: Issue with arrays for creating new variables

Thank you everyone for your comments! They were very helpful.

 

Ask a Question
Discussion stats
  • 6 replies
  • 200 views
  • 4 likes
  • 5 in conversation