Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

re: st: How can I replace missing values with the variable's first nonmissing value?


From   "Airey, David C" <[email protected]>
To   "[email protected]" <[email protected]>
Subject   re: st: How can I replace missing values with the variable's first nonmissing value?
Date   Sat, 11 Aug 2012 15:04:09 -0500

.

> A similar way to do it:
> 
> gen obs = _n
> su obs if !missing(x), meanonly
> replace x = x[r(min)] if _n < r(min)

What's missing in your solution? It doesn't
work when I append to my code...

-Dave


clear
set obs 100
set seed 1967
gen x = runiform()
gen y = runiform()
replace x = . if y > 0.8 // 20% missing
drop y

gen obs = _n
su obs if !missing(x), meanonly
replace x = x[r(min)] if _n < r(min)

              x   obs  
  1.   .1224991     1  
  2.   .9317513     2  
  3.    .268727     3  
  4.          .     4  
  5.          .     5  
  6.   .3401332     6  
  7.   .6752468     7  
  8.   .3403953     8  
  9.   .5833964     9  
 10.   .3562438    10  
 11.   .5706896    11  
 12.   .2602532    12  
 13.   .5183807    13  
 14.   .2311059    14  
 15.   .6327367    15  
 16.   .8565149    16  
 17.   .3864231    17  
 18.   .2451925    18  
 19.   .6647257    19  
 20.   .3576449    20  

clear
set obs 100
set seed 1967
gen x = runiform()
gen y = runiform()
replace x = . if y > 0.8 // 20% missing
drop y
gen notmissing = _n if !missing(x)
egen r1 = min(notmissing)
gen r2 = x[r1]
gen x2 = x
replace x2 = r2 if missing(x)
drop notmissing r1 r2

list in 1/20, clean

              x         x2  
  1.   .1224991   .1224991  
  2.   .9317513   .9317513  
  3.    .268727    .268727  
  4.          .   .1224991  
  5.          .   .1224991  
  6.   .3401332   .3401332  
  7.   .6752468   .6752468  
  8.   .3403953   .3403953  
  9.   .5833964   .5833964  
 10.   .3562438   .3562438  
 11.   .5706896   .5706896  
 12.   .2602532   .2602532  
 13.   .5183807   .5183807  
 14.   .2311059   .2311059  
 15.   .6327367   .6327367  
 16.   .8565149   .8565149  
 17.   .3864231   .3864231  
 18.   .2451925   .2451925  
 19.   .6647257   .6647257  
 20.   .3576449   .3576449  



*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index