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   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: How can I replace missing values with the variable's first nonmissing value?
Date   Sat, 11 Aug 2012 19:35:07 +0100

A similar way to do it:

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

For more examples hinging on a variable constructed to contain _n, see

SJ-6-3  dm0025  . . . . . . . . . . . . . .  Stata tip 36: Which observations?
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  N. J. Cox
        Q3/06   SJ 6(3):430--432                                 (no commands)
        tip for identifying which observations satisfy some
        specified condition

SJ-6-4  dm0025  . . . . . . . . . .  Stata tip 36: Which observations? Erratum
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  N. J. Cox
        Q4/06   SJ 6(4):596                              (no commands)
        correction of example code for Stata tip 36


On Sat, Aug 11, 2012 at 5:08 PM, Airey, David C
<[email protected]> wrote:

> Here is a try:
>
> clear
> set obs 100
> 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
> browse

Yuelian Sharon

>> I want to replace a variable's missing value with its first nonmissing
>> value, how can I realize this? I read the FAQ at
>>
>> http://www.stata.com/support/faqs/data-management/replacing-missing-values/
>> ,
>> but there is no example for my case.
>>
>> My data structure is like :
>>
>> _n  myvar
>> 1    .
>> 2    .
>> 3    .
>> 4    1
>> 5    2
>> 6    6
>> 7    .
>>
>> After replacement, I want to get data as:
>>
>> _n  myvar
>> 1    1
>> 2    1
>> 3    1
>> 4    1
>> 5    2
>> 6    6
>> 7    1
*
*   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