0
votes

I used insheet to read in CSV format data. The names of the variables should be the first line of the dataset. I have a lot of variables and many years of data to read in so I would like to do this using a foreach var loop as follows:

   input str8 x str8 y str8 z
   first second third
   3 6 2
   4 1 2
   8 7 6
   end

   foreach var of varlist * {
     rename variable "`var'" "`=`var'[1]'"
   }

Unfortunately, I receive a syntax error response.

I'm assuming the problem must be in the way I specified the new name. I was extrapolating from this Q&A: http://www.stata.com/statalist/archive/2011-09/msg01109.html

1
insheet has a [no]names option. The help states: "[no]names informs Stata whether variable names are included on the first line of the file."Roberto Ferrer

1 Answers

2
votes

The problem is not to do with foreach. Your input code didn't run for me but that seems a side-issue.

The main problems seem to be

  1. rename does not include the syntax variable unless that is a variable name.

  2. rename does not use double quotes.

See the help for rename.

This works and keeps on going.

clear 
input str8 x str8 y str8 z
"first" "second" "third"
"3" "6" "2"
"4" "1" "2"
"8" "7" "6"
end

foreach var of varlist * {
   rename `var' `=`var'[1]'
}
drop in 1 
destring, replace 
l 

     +------------------------+
     | first   second   third |
     |------------------------|
  1. |     3        6       2 |
  2. |     4        1       2 |
  3. |     8        7       6 |
     +------------------------+

However, insheet is an out-of-date command.

See help import or http://www.stata.com/manuals14/dimport.pdf to see that import delimited is what to use and that it supports variable names on the first line of the data file, so none of this should be needed, unless you have access only to an older version of Stata.

(If you are using an old version, it is always a good idea to be explicit about that in any forum supporting Stata questions.)

EDIT: As @Roberto Ferrer points out insheet also supports variable names on the first line.