Announcement

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

  • Foreach and gen ? Help please

    Hi, I was wondering if is possible making a loop to fill a serie, for example:
    set obs 10
    foreach x in "Enero" "Febrero" "Marzo"{
    gen mes_`x'=`x'
    }
    And get
    mes_Enero filled with all the observations with Enero
    mes_Febrero filled with all the observations with Febrero
    the same with "Marzo"
    Name the series is possible, the problem is about the observations.
    Really need the help
    Thank u
    Last edited by Pamela Serda; 19 Feb 2019, 15:03.

  • #2
    So the problem is that you have quotes where you don't need them and you don't have them where you do need them.

    Code:
    clear
    set obs 10
    foreach x in Enero Febrero Marzo {
        gen mes_`x'="`x'"
    }
    In the future, when posting code, please enclose it between code delimiters to maximize readability and preserve alignment, as I have done here. If you are not familiar with code delimiters, please see Forum FAQ #12 for details.

    Added: It's usually not a good idea to create variables and then fill them in with a constant value. Such things are usually better stored as scalars or local macros. Why are you doing this?

    Comment

    Working...
    X