0

I'm importing files through a loop:

forvalues y=2010/2022 {
    use "file`y'V1.dta"
    [making changes]
    save “file`y'.dta”
}

Problem is that some of the filenames have "V2" or "V3" instead of "V1".

How can I "ignore" this part? In some programming languages, you just write “*” to indicate that anything can be in that spot in the string.

I cannot change the filenames in their original directory since they are on a shared server and they are too big to just copy.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
Victor Nielsen
  • 443
  • 2
  • 14

1 Answers1

1

The most satisfactory solution is to loop over files file20??V?.dta which you can populate in Stata. Compare my answer at https://www.statalist.org/forums/forum/general-stata-discussion/general/1705910-loading-datasets-using-a-loop-with-an-inconsistent-naming-scheme

Otherwise, something like this may help. Necessarily not tested.

forvalues y=2010/2022 {
    capture use "file`y'V1.dta"
    if _rc { 
         capture use "file`y'V2.dta"
         if _rc {
              capture use "file`y'V3.dta" 
              if _rc { 
                  di "`y' data not found"
                  continue 
              }
         }
    }
   
    [making changes]
    save “file`y'.dta”
}

EDIT There are no concrete examples of directory or folder structure in your question. Nor do you state what operating system you are using. But let's suppose you are working in directory myplace but using files from otherplace. Forward slashes always work in Stata in this context.

local files : dir otherplace files "file20??V?.dta" 

foreach f of local files { 
    use otherplace/`f' 
    local year = substr("`f'", 5, 4)
    * changes 
    save otherplace/file`year'
} 
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
  • your link seems like a good solution, but how do I refer to that directory in the foreach loop? – Victor Nielsen Mar 16 '23 at 17:10
  • It’s a good idea to work in the same directory as your files. If you can’t do that you need to tell Stata where the files are. – Nick Cox Mar 16 '23 at 17:41
  • Im Sorry to ask, but would you mind showing me how I do that? It’s just that I’m not so familiar with the directory code and how it works. – Victor Nielsen Mar 16 '23 at 17:49
  • See the first example at `help use`. In your case you would need the pattern `use "` _somewhere_ `/file\`y'V1.dta"` where _somewhere_ indicates where to find the file. – Nick Cox Mar 16 '23 at 18:52
  • local files : dir . files "data*.dta" I don't see where the "use" goed in this code. – Victor Nielsen Mar 16 '23 at 21:51
  • My edit may move nearer what you want, but the question needs to be more concrete about your set-up. – Nick Cox Mar 17 '23 at 00:58