Announcement

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

  • Loop across multiple files

    Hi all,

    I am trying to create a loop to run across two different files "PSQ_A" and "PSQ_B".

    I want the loop to open each file and run the function 'describe'. I want to then generate a new variable 'Clinic' where the value is 'A' for file "PSQ_A" and 'B' for file "PSQ_B".

    I have thought about using command 'forvalues', but I can't seem to get this to work.


    Code:

    forvalues i=A/B {
    use PSQ_`i', clear
    describe
    gen Clinic=`i'
    }

    However I get invalid syntax.. Is this the correct command to use over multiple files?


  • #2
    No; it's not. forvalues is for looping over lists of integers of specific form.

    Code:
    help forvalues
    This is more likely to work:

    Code:
    foreach i in A  B {
    use PSQ_`i', clear
    describe
    gen Clinic = "`i'"
    }
    Note that yourgenerate command will fail to do what you want -- it's either illegal or irrelevant, depending. You need the clinic to be a string variable and the double quotes are needed to ensure that.

    Detail: describe is a command, not a function. Regardless of terminology elsewhere, that's the Stata terminology.

    Detail: in principle, forvalues does support some loops over non-integers, but don't try that until and unless you know how it might fail to give you what you want.
    Last edited by Nick Cox; 26 May 2024, 06:09.

    Comment

    Working...
    X