How To / STATA: Check if a File Exists Before Opening It

The STATA’s command –capture- allows you to check if the file that you are trying to open exists. This command evaluates whether or not the file is in the folder you are using. Then, –capture- assigns a value to the macro _rc depending on whether the file is in the folder or not. Therefore, we can use the value of _rc to continue with our STATA’s script.

Suppose you have several files in a folder that you want to open in STATA. The files are named “File_i.dta” where i is a number from 1 to 20. However, there are not 20 files in the folder but 15. You might be able to identify which files are missing and then adjust some things in the script in order to manage the exceptions that will arise because of those missing files. But, what if you have plenty of exceptions? –capture- can help you. With this command you can confirm that a file exists in a folder so then you can use the file. Next, I show a small STATA’s script that opens the files and adds a new variable equals to 1.

forvalues i=1/20 {
  capture confirm file "File_`i'.dta"
  if _rc==0 {
    use "File_`i'.dta"
    gen MyVar = 1
    save "File_`i'.dta", replace
  }
  else {
    display "The file File_`i'.dta does not exist"
  }
}

The script uses a loop –forvalues– that evaluates the variable i from 1 to 20. Every time the variable i takes a new value, –capture– check whether or not the file named “File_i.dta” exists. If the file exists, then _rc is equal to 0. In this case, the script opens the file and then add the variable MyVar to the file. If the file does not exist, the script display the message “The file File_i.dta does not exist”.

The command –capture– is particularly useful when you are importing or merging several files. It helps you to build a flexible script. That is, you do not need to code the exceptions (e.g. File_11.dta does not exist).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s