BookmarkSubscribeRSS Feed
thanikondharish
Fluorite | Level 6

data s ;
input name $ 15. ;

cards ;
dfsdfdas
dfsdfasdf
sdfwtrw
ghjghj
fghfdh
etwrt
rtyurtuy
rtrt
rtrysrt
rtrrt
;
run;

 

 

how to assign random numbers like below table ?

name

random

dfsdfdas

1

dfsdfasdf

2

sdfwtrw

1

ghjghj

2

fghfdh

1

etwrt

2

rtyurtuy

1

rtrt

2

rtrysrt

1

rtrrt

2

2 REPLIES 2
hashman
Ammonite | Level 13

@thanikondharish:

 

I fail to observe any "randomness" in your assigned numbers. You merely assign 1 and 2 to the records whose observation numbers are odd and even, respectively. All you need to do to achieve that is:

data r ;                  
  set s ;        
  random = 2 - mod (_n_, 2) ;
run ;                        

However, if you really need RANDOM to be random in the [1:2] range, it should instead be:

data r ;                             
  set s ;                   
  random = ceil (rand ("uniform") * 2) ;
run ;                                   

  Paul D.

ballardw
Super User

Or

data r ;                             
  set s ;                   
  random = rand ("table",0.5,0.5) ;
run ; 

Rand table is good for generating integers with known probabilities. The above results in 1 or 2 with probabilities of 0.5 and 0.5.

 

If you wanted a different distribution such as 60% 1 and 40% 2 then

data r ;                             
  set s ;                   
  random = (rand ("table",0.6,0.4) ;
run ; 

You can use any number of probabilities as long as they total to 1 though for values with repeating decimals such as 1/3 using a variable or the calculation in the table options:

 

random = rand ("table",1/3,1/3,1/3) ;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 1229 views
  • 4 likes
  • 3 in conversation