DATA Step, Macro, Functions and more

SAS: Insert multiple columns or rows in a specific position of an existing dataset

Reply
User
Posts: 1

SAS: Insert multiple columns or rows in a specific position of an existing dataset

Goal: Add one or more empty rows after a specific position in the dataset

Here's the work I've done so far:

 

data test_data;
    set sashelp.class;
    output;

    /* Add a blank line after row 5*/
    if _n_ = 5 then do;
        call missing(of _all_);
        output;
    end;

    /* Add 4 blank rows after row 7*/

    if _n_ = 7 then do;
        /* inserts a blank row after row 8 (7 original rows + 1 blank row) */
        call missing(of _all_);

        /*repeats the newly created blank rows: inserts 3 blank rows*/
        do i = 1 to 3;
            output;
        end;
    end;
run;

 

I'm still learning how to use SAS, but I "feel" like there's a better way to get to the same result, chiefly not having to use a for loop to insert multiple empty rows. I was wondering:

 

  1. Is there a better way to do this for rows?
  2. Is there an equivalent for columns?
  3. These rows/columns are being added more to fit a report format. The dataset doesn't need these blank rows/columns for its own sake. Is some PROC or REPORT function that achieves the same thing?

 

Super Contributor
Posts: 440

Re: SAS: Insert multiple columns or rows in a specific position of an existing dataset

Firstly I'd NEVER insert empty rows or columns in a data set just to make a report "fit". It makes any further processing of the data much more difficult and is simply unnecessary. Proc Report is incredibly versatile and give you just about any layout you want - for example this paper shows how you can simulate empty columns in your report http://www2.sas.com/proceedings/sugi31/092-31.pdf

 

You can also simulate blank lines based on a condition using similar techniques

Super User
Posts: 11,343

Re: SAS: Insert multiple columns or rows in a specific position of an existing dataset


yescobar wrote:

 

  1. Is there an equivalent for columns?

 

SAS datasets every record will have the same number of variables in the output. So if you are thinking of "conditional" variables then no.

If you add any statemen using variable then that varaible will be created if it does not alread and have a missing value unless assigned one.

Label BlankVar='this is a blank';

or

Format BlankVar best5.;

or an attribute statement, using the variable name on an array reference, retain or any number of other statements

will add a variable and get a message in the log about variable blankvar has never been referenced if you do not assign a value.

A conditional:

If x=3 then newvar=5;

will add newvar to all records but the only values would be when x=3 and have 5.

Ask a Question
Discussion stats
  • 2 replies
  • 123 views
  • 1 like
  • 3 in conversation