Help using Base SAS procedures

Assigning alphanumeric values

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 14
Accepted Solution

Assigning alphanumeric values


Hi, I want to assign a value in the sequence {X1, Y1, X2, Y2}, starting with a random value from that sequence then cycle through the sequence over and over for the number of observations. For example:

if the random value from the sequence {X1, Y1, X2, Y2} is Y1, then the next value should be X2, then Y2, then X1, then Y1, then X2 and so on. 

Not sure how to do the alphanumeric assignment.

Thanks,

Josh


Accepted Solutions
Solution
‎06-22-2015 11:49 AM
Super User
Posts: 17,828

Re: Assigning alphanumeric values

Set up a temporary array to hold your sequence. Then use a random distribution to get your first index and then increment from there, using the mod function to stay within the limits of your array.

data have;

do i=1 to 100;

output;

end;

run;

data want;

set have;

array seq(4) $ _temporary_ ("X1" "Y1" "X2" "Y2");

retain start;

if _n_=1 then start=floor(rand('uniform')*dim(seq))+1;

else start=mod(start,dim(seq))+1;

sequence=seq(start);

run;

View solution in original post


All Replies
Solution
‎06-22-2015 11:49 AM
Super User
Posts: 17,828

Re: Assigning alphanumeric values

Set up a temporary array to hold your sequence. Then use a random distribution to get your first index and then increment from there, using the mod function to stay within the limits of your array.

data have;

do i=1 to 100;

output;

end;

run;

data want;

set have;

array seq(4) $ _temporary_ ("X1" "Y1" "X2" "Y2");

retain start;

if _n_=1 then start=floor(rand('uniform')*dim(seq))+1;

else start=mod(start,dim(seq))+1;

sequence=seq(start);

run;

Super User
Posts: 10,500

Re: Assigning alphanumeric values

One way, possibly not the slickest:

data want;

     set have;

     retain pos;

     if _n_ = 1 then pos= mod(rand('table', 0.25, 0.25, 0.25, 0.25),4);

     else pos = mod(pos+1,4);

     select (pos);

          when(0) sequence='X1';

          when(1) sequence='Y1';

          when(2) sequence='X2';

          when(3) sequence='Y2';

          otherwise;

     end;

run;

You may want to drop the POS variable. Alternatively, skip the select and assignment to sequence and use a custom format on the POS variable (named as you like) that would display the X1, Y1 etc. That would actually be my choice.

Respected Advisor
Posts: 4,647

Re: Assigning alphanumeric values

Simple task:

data have;

do i = 1 to 10; output; end;

run;

data want;

array values{4} $ _temporary_ ("X1", "Y1", "X2", "Y2");

if rndOffset=0 then rndOffset + ceil(dim(values)*rand("UNIFORM"));

set have;

rndValue = values{1 + mod(_n_ + rndOffset, dim(values))};

drop rndOffset;

run;

PG

PG
☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 254 views
  • 6 likes
  • 4 in conversation