Announcement

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

  • Saving tempfiles inside a loop

    Hi everyone,

    I am currently working on dataset wherein I have imported three datasets and for each of these I have to run a similar set of commands. For this, I first create tempfiles of each of these datasets; store them in a local and run a loop consisting of the common commands to run on the three datasets. The problem (which is a syntax error, most probably) is that when I try to save a new version of these tempfiles in the loop, I am unable to do so. I am sharing the code that I am using. It would be helpful if someone could let me know where I am going wrong in saving the new tempfiles inside the loop.

    Code:
    local file `a' `b' `c'  // creating a local to store tempfiles (which are created earlier in the code)
        
        foreach f in `file'{
            use `f', clear
            
            ren c_no c_id // running common commands
            ren p_no p_id
            
            replace c_id = subinstr(c_id , " ", "", .)
            
             tempfile `f'1 // saving new tempfiles to be used later in the code
            save ``f'1', replace
    }
     
    use `a1', clear
    I am getting the following error when I run the loop:
    Code:
     _: invalid name r(198);
    Please let me know.

    Thanks!

  • #2
    In your line of code the `f' evaluates to something like C:\Users\rachita~1\AppData\Local\Temp\ST_7ac_00000 1.tmp. That's too long and has disallowed characters for use as a handle for a temporary file name.

    Instead use something like
    Code:
    tempfile a b c
    
    . . .
    
    local file a b c
        
    foreach f in `file' {
    
        use ``f'', clear
    
        ren c_no c_id
        ren p_no p_id
    
        replace c_id = subinstr(c_id , " ", "", .)
     
        tempfile `f'1
        save ``f'1', replace
    }
    
    use `a1', clear

    Comment


    • #3
      Sorry, I omitted the line of code that I was referring to. See below for correction.

      In your line of code
      Code:
      tempfile `f'1
      the `f' evaluates to something like C:\Users\rachita~1\AppData\Local\Temp\ST_7ac_000001.tmp.

      Comment


      • #4
        Thanks a lot, Joseph! This worked!

        Comment

        Working...
        X