Code:
------------------------------------------------------------------------------------------------------------------------------------
      name:  <unnamed>
       log:  /Users/ll/Downloads/log.smcl
  log type:  smcl
 opened on:  30 Mar 2021, 21:28:40

. cd "/Users/ll/Downloads/"
/Users/ll/Downloads

. use significance7.dta, clear

. append using significance8
.
. tempvar tempid tempMediatorTotal

. egen `tempid' = group(IV Moderator Controls),missing

. gen `tempMediatorTotal'=Mediator

. bys `tempid': replace `tempMediatorTotal' = `tempMediatorTotal'[_n-1]+ " " +`tempMediatorTotal' if _n>1
(27,500 real changes made)

. bys `tempid': replace `tempMediatorTotal' = `tempMediatorTotal'[_N]
(27,500 real changes made)

.
. keep if strpos(`tempMediatorTotal',"pos")>0 & strpos(`tempMediatorTotal',"neg")>0
(18,664 observations deleted)

.
.
. tempvar length length1 length2

. gen `length'=length(IV)

. gen `length1'=length(Controls)

. gen `length2' = length(Mediator)

. hashsort -`length' IV Moderator   -`length1' -`length2' Mediator
(note: missing values will be sorted first)

.
. gegen tempid = group(IV Moderator Controls),missing

. su tempid

    Variable |        Obs        Mean    Std. Dev.       Min        Max
-------------+---------------------------------------------------------
      tempid |     12,008    395.5428    212.1199          1        728

. order tempid

.
. keep if pvalueInteraction < .05
(5,647 observations deleted)


. tempvar tempid tempMediatorTotal

. egen `tempid' = group(IV Moderator Controls),missing

. gen `tempMediatorTotal'=Mediator

. bys `tempid': replace `tempMediatorTotal' = `tempMediatorTotal'[_n-1]+ " " +`tempMediatorTotal' if _n>1
(5,753 real changes made)

. bys `tempid': replace `tempMediatorTotal' = `tempMediatorTotal'[_N]
(5,753 real changes made)

.
. keep if strpos(`tempMediatorTotal',"pos")>0 & strpos(`tempMediatorTotal',"neg")>0
(2,781 observations deleted)

.

. log close _all
      name:  <unnamed>
       log:  /Users/ll/Downloads/log.smcl
  log type:  smcl
 closed on:  30 Mar 2021, 21:29:19
------------------------------------------------------------------------------------------------------------------------------------
As you can see, at the second time I run command keep, there are some observations deleted, why those observations are not deleted at the first time?
It it because the usage of egen group ?