Announcement

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

  • tempname frames question

    Can someone explain why posting to a temporary frame doesn't work in the code below whereas posting to a permanent frame works? The code is just a reproducible example where I am grabbing the first line of multiple .csv files, along with the file name, and making a dataset of those.

    Code:
    version 16.1
    
    mkdir temp_stata
    
    cd temp_stata
    
    clear
    input str10 v1
    "one"
    "two"
    "three"
    "four"
    end
    export delimited using "myfile1.csv"
    clear
    input str10 v1
    "five"
    "six"
    end
    export delimited using "myfile2.csv"
    
    *** this works
    
    frame create results str100 v1 str100 f 
    frames dir
    frame change default
    
    local myfiles : dir . files "*.csv"
    foreach f of local myfiles {
        display "`f'"
        quietly import delimited "`f'", varnames(1) clear
        quietly keep in 1
        frame post results (v1[1]) ("`f'") 
    }
    
    frame change results
    compress
    list
    
    *** this doesn't
    
    /*
    tempname results
    frame create `results' str100 v1 str100 f 
    frames dir
    frame change default
    
    local myfiles : dir . files "*.csv"
    foreach f of local myfiles {
        display "`f'"
        quietly import delimited "`f'", varnames(1) clear
        quietly keep in 1
        frame post `results' (v1[1]) ("`f'") 
    }
    
    frame change `results'
    compress
    list
    */

  • #2
    I think you'll find that it does work, but perhaps not in the way that you expect. I have run your code, first using the permanent name for the frame, and then again using the tempname approach. The output that results is the same:

    Code:
    . compress
      variable v1 was str100 now str4
      variable f was str100 now str11
      (370 bytes saved)
    
    . list
    
         +--------------------+
         |   v1             f |
         |--------------------|
      1. |  one   myfile1.csv |
      2. | five   myfile2.csv |
    If I am not mistaken, the issue has to do with the longevity of the -tempname-, which gets created when the do-file is execute, and destroyed upon its completion. Once complete, the frame no longer exists because its name no longer exists (and presumably that memory space is freed up). I recently encountered this same behaviour for my own simulation.

    What you may do, if you like the tempname approach, is accumulate results as you were, and when complete, copy the frame into a permanent frame or save out that frame as a dataset if you wish to keep it permanently.

    Comment


    • #3
      Oh, I see that now. Thanks!

      Comment

      Working...
      X