2017-02-28 71 views
1

你能幫我。 我想生成隨機陣列從0〜5和我使用這個功能SAS隨機數組與非重複元素

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

但我想以產生具有非輪迴元件隨機陣列。 例如(1,2,3,4,5) (3,1,5,4,2)等。

我該怎麼辦呢? 謝謝!

+1

在這個問題中還要考慮@data_null的答案。 '調用randperm'對你來說是個不錯的選擇。 https://stackoverflow.com/questions/42086988/randoming-symbols-from-a-z/42091012#42091012 – Longfish

回答

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; 
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;