Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


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

Re: st: How can I get the second last non-missing value?


From   Rebecca Pope <rebecca.a.pope@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: How can I get the second last non-missing value?
Date   Thu, 13 Jun 2013 09:13:00 -0500

Any time I would have saved by using Mata would have been completely
lost to time figuring out how to accomplish it in Mata.

Sergiy, would you mind providing a little explanation for what your
code is doing? I made some notes below about what I think is going on,
but I just want to make sure I'm following you.

***
 mata

void prelast() {   <= like -capture program drop-?, you're just
clearing out any previous definition of the program?
V=.   <= define a null matrix V
st_view(V,.,st_local("varlist"))   <= make a view onto the data
(presumably here to save memory?), all observations on the variables
given in the Stata local macro varlist (supplied elsewhere)
R=.
st_view(R,.,st_local("result"))   <= this bit confused me at first b/c
I thought the variable had to exist already, but you handle this by
generating a result variable with all values missing before you run
prelast(), correct?

for(i=1;i<=rows(V);i++) {  <= loosely, for every observation in the dataset

for(j=0;j<cols(V);j++) {  <= loosely, for all variables given in
`varlist' except the last one
if (missing(V[i,cols(V)-j])==0) {   <= j is increasing so the column
index here is decreasing, in effect, counting backwards
// found last non-missing

if (cols(V)-j-1<1) break; //nothing before

for(k=cols(V)-j-1;k>=1;k--) {   <= lost me here, why increment k,
don't you know you want cols(V)-j-1 since cols(V)-j is the last
non-missing value?
if (missing(V[i,k])==0)
R[i,1]=V[i,k]  <= replace the ith observation (row) in the R vector
with the appropriate value from V
break;
}

break;
}
}
}
}

end
***

Thanks,
Rebecca

< snip >
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index