Announcement

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

  • foreach for list of different variables

    Hey Everyone,

    This is my data set:
    Click image for larger version

Name:	Capture.JPG
Views:	1
Size:	404.1 KB
ID:	1419173



    I have different variables of consumption, and i want to use a loop to replace all the ".." to "".

    how do I use foreach on this kind of variables?

    I was trying the following:
    foreach var of varlist CONSUM1996 CONSUM1997 CONSUM1998 CONSUM1999 CONSUM2000 CONSUM2001 CONSUM2002 CONSUM2003 CONSUM2004 CONSUM2005 CONSUM2
    > 006 CONSUM2007 CONSUM2008 CONSUM2009 CONSUM2010 CONSUM2011 CONSUM2012 CONSUM2013 CONSUM2014 CONSUM2015 CONSUM2016 {
    2. replace var = "" if var == ".."
    3. }

    Thanks in advance,
    Mor
    Last edited by Mor Dudkin; 21 Nov 2017, 19:42.

  • #2
    First, your screenshot of the data set is unreadable, at least on my computer. That is one reason that the FAQ specifically says not to use screenshots for this purpose. More important, if I needed to import your data to Stata to try out code, a screenshot is useless. The helpful way to post example data is with the -dataex- command. Please read the entire FAQ, with special attention to #12. You will also learn there about using code delimiters to make posted example code more readable.

    That said, the problem with your loop is that inside the loop you have to refer to var by enclosing it in local macro quotes: `var'.

    Also, if all of the variables that begin with CONSUM in your data set are intended to be part of this process, then you can greatly shorten the code as follows:

    Code:
    foreach var of varlist CONSUM* {
        replace `var' = "" if `var' == ".."
    }

    Comment

    Working...
    X