Search code examples
sassgplot

Generate a plot from random numerical vector in SAS


I'm quite new to SAS, I have learned about SGplot, Datalines, IML and randgen. I'd like to simply generate a random data for a simple scatter plot.

/* declaring manually a numeric list */
    data my_data;
        input x y @@;
        datalines;
        1 1 0 8 1 6 0 1 0 1 2 5
        0 3 1 0 1 0 1 4 2 4 1 0
        0 0 0 1 1 2 1 1 0 4 1 0
        1 4 1 0 1 3 0 0 0 1 0 1
        1 0 1 1 2 3 0 2 1 4 2 6
        2 6 1 0 1 1 0 1 2 8 1 3
        1 3 0 5 1 0 5 5 0 2 3 3
        0 1 1 0 1 0 0 0 0 3
        ;
        run;
        
        
        proc sgplot data=my_data;
        scatter x=x y=y; 
        run;

Now I would like in a similar manner to generate a vector of random numbers, such as:

proc iml;
N = 94;
rands = j(N,1);
call randgen(rands, 'Uniform');  /* SAS/IML 12.1 */
run;

and afterwards to transfer the vector as datalines and afterwards pass it into the SGplot. Can somebody please demonstrate how to do it?


Solution

  • Since you want to pass it directly to datalines, use the submit and text substitution options in IML. This passes rands as an Nx1 vector into the datalines statement, allowing you to read it as one big line.

    proc iml;
        N = 94;
        rands = j(N,1);
        call randgen(rands, 'Uniform');  /* SAS/IML 12.1 */
    
        submit rands;
            data my_data;
                input x y @@;
                datalines;
                &rands
                ;
            run;
        endsubmit;
    
    quit;
    
    proc sgplot data=my_data;
        scatter x=x y=y;
    run;
    

    Note you'll need to double your size of N to get exactly 94, otherwise you will have 47. This is because it is reading each pair on the same line before moving to the next line. e.g.:

    1 2 3 4
    
    x = 1 y = 2
    x = 3 y = 4 
    

    Source: Passing Values into Procedures (Rick Wicklin)