Our World Statistics Day conversations have been a great reminder of how much statistics can inform our lives. Do you have an example of how statistics has made a difference in your life? Share your story with the Community!
Choose Language Hide Translation Bar
Highlighted

## Increment a counter from 1 to n for every unique set of identical rows

Hi everyone,

I figure what I want to do is really easy, I just haven't come up with a good way to do it. I have a large table with a substantial number of identical rows which I want to rename uniquely but in a reproducible way. Currently, I have a script that takes the following column:

A number 1

B number 1

A number 2

A number 3

A number 3

A number 3

B number 3

B number 3

B number 3

...

Into into a new names column, using the row index identifier:

A number 1

B number 1

A number 2

A number 3

A number 3 5

A number 3 6

B number 3

B number 3 8

B number 3 9

That code is

``````Names Default To Here( 0 );
RawFile << New Column( "itemname2", Character, Nominal );
Current Data Table( RawFile );
For( i = 2, i <= N Rows( RawFile ), i++,
If( :itemname[i] == :itemname[i - 1],
:itemname2[i] = :itemname[i] || " " || Char( i ),
:itemname2[i] = :itemname[i];
);
);``````

This works well enough, but the issue here is I want the output to instead increment from 1 each time it needs to be used, to give something like

A number 1

B number 1

A number 2

A number 3

A number 3 1

A number 3 2

B number 3

B number 3 1

B number 3 2

I know this should be simple, but I'm not sure how to structure/limit the loop....any help would be appreciated. Thanks!

1 ACCEPTED SOLUTION

Accepted Solutions
Highlighted

## Re: Increment a counter from 1 to n for every unique set of identical rows

Nevermind.....realized I just needed the initialization of the second counter outside the loop. Cheers!

``````Names Default To Here( 0 );
RawFile << New Column( "itemname2", Character, Nominal );
Current Data Table( RawFile );k=1;
For( i = 2, i <= N Rows( RawFile ), i++,
If( :itemname[i] == :itemname[i - 1],
:itemname2[i] = :itemname[i] || " " || Char( k );                k++,
:itemname2[i] = :itemname[i];                k=1
);
);``````
Highlighted

## Re: Increment a counter from 1 to n for every unique set of identical rows

Nevermind.....realized I just needed the initialization of the second counter outside the loop. Cheers!

``````Names Default To Here( 0 );
RawFile << New Column( "itemname2", Character, Nominal );
Current Data Table( RawFile );k=1;
For( i = 2, i <= N Rows( RawFile ), i++,
If( :itemname[i] == :itemname[i - 1],
:itemname2[i] = :itemname[i] || " " || Char( k );                k++,
:itemname2[i] = :itemname[i];                k=1
);
);``````
Article Labels

There are no labels assigned to this post.