SAS随机数组,具有非重复元素

时间:2017-02-28 10:11:36

标签: sas sas-macro

你能帮我吗? 我想从0到5生成一个 随机数组 ,我正在使用这个函数

rand_num = int(ranuni(0)*5+1)

但我想生成一个带有 非重复 元素的随机数组。 例如(1,2,3,4,5) (3,1,5,4,2)等..

我怎么做? 谢谢!

2 个答案:

答案 0 :(得分:0)

/* draw with repetition */
data a;
    array rand(5);

    do i = 1 to dim(rand);
        rand(i) = int(ranuni(0)*5+1);
    end;

    keep rand:;
run;

/* draw without repetition */
data a;
    array rand(5);

    do i = 1 to dim(rand);
        do until(rand(i) ^= .);
            value = int(ranuni(0)*5+1);
            if value not in rand then
                rand(i) = value;
        end;
    end;

    keep rand:;
run;

答案 1 :(得分:0)

我认为call ranperm是更好的解决方案,尽管两者似乎具有大致相同的统计属性。这是一个使用它的解决方案(非常类似于Keith在@data_null_'s solution on another question中指出的):

data want;
  array rand_array[5];

  *initialize the array (once);
  do _i = 1 to dim(rand_array);
    rand_array[_i]=_i;
  end;

  *seed for the RNG;
  seed=5;

  *randomize;
  *each time `call ranperm` is used, this shuffles the group;
  do _i = 1 to 1e5;
    call ranperm(seed,of rand_array[*]);
    output;
  end;
run;