5

I am new to SAS I have SAS data like (It does not contain Obs column)

Obs    ID    Name    Score1    Score2    Score3

1     101               90        95        98
2     203               78        77        75
3     223               88        67        75
4     280               68        87        75
.
.
.
.
100   468               78        77        75

I want data having row number 2 6 8 10 34. Output should look like

Obs    ID    Name    Score1    Score2    Score3

1     203               78        77        75
2     227               88        67        75
3     280               68        87        75
.
.
.

Thanks in advance.

NorthCat
  • 9,643
  • 16
  • 47
  • 50
Sangram
  • 407
  • 1
  • 6
  • 18

2 Answers2

7

The other answer is ok for small tables, but if you are working with a very large table it's inefficient as it reads every row in the table to see whether it has the right row number. Here's a more direct approach:

data example;
    do i = 2, 6, 8, 10;
        set sashelp.class point = i;
        output;
    end;
    stop;
run;

This picks out just the rows you actually want and doesn't read all the others.

user667489
  • 9,501
  • 2
  • 24
  • 35
  • 2
    As the OP is a newbie to SAS, it's probably worth mentioning the importance of the `stop` statement. Because SAS is directly accessing the specific records, it won't read the end of file marker that normally ends a query automatically. Without `stop` the query would never end. – Longfish Mar 11 '15 at 09:29
  • @D.O. the only way to do that would be to use data set options - e.g. `select * from mytable(obs=n firstobs=n)` to get row `n`. SQL itself has no concept of row numbers. – user667489 Mar 19 '20 at 15:37
6

You can loop through each line of data with a data step and only output the lines when you are in the n'th loop with a condition like this.

data test;
    set LIB.TABLE;
    if _N_ in (2, 6, 8, 10, 34) then output;
    run;

where _N_ will correspond to the number of the line in this case.

stallingOne
  • 3,633
  • 3
  • 41
  • 63
  • 4
    Since OP is new to SAS, it's worth pointing out that _n_ is NOT actually a row number. It's a counter of the number of times the data step has iterated. People often use it as a row number in simple data steps like this. Just good to know that it's not really a row number, in more complex data steps _N_ may not correspond at all to data step row number. – Quentin Mar 11 '15 at 10:43
  • An answer containing only code is not a good answer. Please explain how the code works and include any information necessary to correctly use the code in your answer. – Joe Mar 11 '15 at 14:19