0

I am trying to import multiple files in csv format into Stata. Their names follow the format "variable_2010". I want to use a loop to import and save these files. I tried the following:

foreach var in varlist a b c d {
import "c:\`var'_2010.csv"
save ......
}

This does not work . The problem is that var is not recognised inside the path. How could I escape this problem?

1
  • var is here a local macro. People used to other languages may want to call it a variable, but it's not a variable to Stata, but, as said, a local macro. Commented Feb 17, 2015 at 17:16

2 Answers 2

2

There seems to be confusion with the use of foreach. You probably meant

foreach var in a b c d {
   import "c:/`var'_2010.csv"
}

The keyword varlist is meant to be used with of and not in. If used in your original way, varlist is just text to be used in the looping, which I assume is not what is meant. Read help foreach carefully.

You have already discovered the "backstabbing backslash", and that its use is discouraged. Depending on the OS, Stata will translate accordingly, so you should always use / when working with file directories.

Reference:

Stata tip 65: Beware the backstabbing backslash, The Stata Journal, by Nicholas J. Cox.

Sign up to request clarification or add additional context in comments.

Comments

0

After searching through similar questions, I seem to have found the answer. This link here http://www.stata-journal.com/article.html?article=pr0042 solve the problem. Just use forward slash instead of backlash.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.