No announcement yet.
  • Filter
  • Time
  • Show
Clear All
new posts

  • A bug with st_view or (more likely) my stupidy

    Dear Statalist

    I have come across some strange behaviour by st_view, which is contrary to what I (perhaps naively) assumed. The issue can be demonstrated using the following code:

    mata clear

    void testprog() {
    stata("stset time")

    (void) st_addvar("double", "x1")
    st_view(x1, ., "x1")
    x1[.,.] = rnormal(100,1,1,1)
    stata("stset time")


    set obs 100
    gen time=runiform()
    mata: testprog()
    summ x1

    Running this, one first sees the output from the first call of stset by the Mata program testprog. One then sees the mean of the 100 generated random normal draws. One then sees the stset output again. But then the final call in the Mata program, to again give the mean of x1 (a view onto the newly generated variable x1), one obtains the wrong value (a value of zero). What I think is happening is that although one can call st_view with a string variable name, it is really binding the Mata object to view a particular variable number in the Stata dataset. Thus if the ordering of the variables in the Stata dataset changes, the st_view object may now be pointing to a different variable in Stata's dataset, and in particular not the one which was originally intended when the st_view was called with a string variable name.

    Assuming the above explanation is correct, perhaps I was being naive in how I expected st_view to work. Otherwise, perhaps it would be wise to warn users about this behaviour in the help file?