Skip to content
Prev 388441 / 398503 Next

add a variable a data frame to sequentially count unique rows

I am not sure I understand... you are referring to files but we are not 
discussing files here. There are "input" and "output" phases yet to be 
dealt with that separate the analysis you do in R from the files 
themselves. We are discussing data frames here.

Regardless, you either have duplicates in your input (faulty data) or you 
do not have duplicates because there are additional distinguishing columns 
that you have not identified. (https://en.wikipedia.org/wiki/Primary_key)

The solution to the problem that you should not have involves making a 
sensible (not faulty) copy of your data, setting up the count column, and 
then joining the faulty data with the sensible data.

Note that the ordering of the result happens to be retained when using 
dplyr::left_join, but is not retained using most other join 
implementations (such as base::merge). There can be significant 
performance gains to be had by giving up on record ordering, which is one 
of the reasons why having a valid primary key can be so important.

library(dplyr)
lookup_df <- (   test
              %>% select( group1, group2 )
              %>% filter( !duplicated( . ) )
              %>% group_by( group1 )
              %>% mutate( count1 = seq.int( n() ) )
              %>% ungroup()
              )
ans <- left_join( test, lookup_df, by = c( "group1", "group2" ) )
On Fri, 2 Jul 2021, Yuan Chun Ding wrote:

            
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k