New Contributor
Posts: 2

# how to make a loop to duplicate previous rows

[ Edited ]

I am a new SAS user , firstly forgive me for my poor English grammar please, then the following is my problem.

I want to write a loop to make the table like that:

have:

id name

1 Jam

2 John

3 Will

want:

newid id name

1 1 Jam

2 1 Jam

3 2 John

4 1 Jam

5 2 John

6 3 Will

P.S. the logic should be following:

the logic should be when i have N row in raw table;

when I try to create new table, then i write the first row like the first row of raw table;

then i try to create second step that copy first row and second rows of raw table and they should be second and third rows in new table;

then when i create third step that copy first,second and third rows of raw table and  they shoud be forth,fifth and sixth rows in new table;

etc

the Nth step should be that copy first row to Nth rows of raw table, then the whole number of rows should be (1+N)*(N/2), the first row of raw table is copied in N times and second one should be (N-1) times;

Posts: 5,541

## Re: how to make a loop to duplicate previous rows

``````data have;
input id name \$;
datalines;
1 Jam
2 John
3 Will
;

data want;
set have nobs=nobs;
do i = _n_ to nobs;
newId = (i * i-1)/2 + _n_;
output;
end;
drop i;
run;

proc sort data=want; by newId; run;

proc print; run;``````
PG
Super User
Posts: 23,776

## Re: how to make a loop to duplicate previous rows

[ Edited ]

Whats the logic? You can control the output of a line using the OUTPUT statement, but it depends on the logic.

For example, this outputs the first two rows of the sashelp.class data set the number of times of the variable age.

``````data want;
set sashelp.class (obs=2);

do i=1 to age;
output;
end;

drop i;
run;``````

@Howiewang wrote:

I am a new SAS user , firstly forgive me for my poor English grammar please, then the following is my problem.

I want to write a loop to make the table like that:

have:

id name

1 Jam

2 John

3 Will

want:

newid id name

1 1 Jam

2 1 Jam

3 2 John

4 1 Jam

5 2 John

6 3 Will

New Contributor
Posts: 2

## Re: how to make a loop to duplicate previous rows

the logic should be when i have N row in raw table;

when I try to create new table, then i write the first row like the first row of raw table;

then i try to create second step that copy first row and second rows of raw table and they should be second and third rows in new table;

then when i create third step that copy first,second and third rows of raw table and  they shoud be forth,fifth and sixth rows in new table;

etc

the Nth step should be that copy first row to Nth rows of raw table, then the whole number of rows should be (1+N)*(N/2), the first row of raw table is copied in N times and second one should be (N-1) times;

that's the logic what i want,