Announcement

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

  • Merging files using loop

    Dear all,

    I am trying to merge files in one folder with files in another folder (all stata files). Below is the codes I have used. I am getting "invalid syntax" . Will be very grateful for help on this. Thank you very much.


    global original "/research/alldata_stataversions/data"
    global working "/data file/new"

    local files : dir "$original/folder1/" files "*.dta"
    foreach file in `files' {

    use "$original/folder1/`file'",clear
    display `files'

    local usingfile: dir "$original/folder2/" files "*.dta"
    foreach u in `usingfile' {
    cd "$original/folder2/`usingfile'"
    merge 1:m id using "/`u'"

    }
    }

  • #2
    The -set trace on- command will show you where your syntax errors are occurring, and is the first thing to do when you are trying to discover what kind of a syntax problem is happening. It will show the contents of your macros as they are expanded, among other things, which is very helpful in diagnosis. See -help set trace-.

    When I did that, I was able to realize that the line:
    Code:
    cd "$original/folder2/`usingfile'"
    expanded to contain several file names in quotes where `usingfile' occurred, something like this:
    Code:
    cd "/research/alldata_stataversions/data/ "ThisFile.dta" "ThatFileFile.dta" "TheOtherFile.dta""
    I suspect you intended just:
    Code:
    cd "$original/folder2/"
    A note regarding a harmless error:
    I suspect you wanted
    Code:
    display `file' // not `files'
    In order to see which "file" in "files" was being used.

    Comment


    • #3
      Thank you very much. I have used the codes below nut is it is still not working. Will be very grateful for help on this


      global original "/research/alldata_stataversions/data"
      global working "/data file/new"

      local files : dir "$original/folder1/" files "*.dta"
      foreach file in `files' {

      use "$original/folder1/`file'",clear
      display `file'

      local usingfile: dir "$original/folder2/" files "*.dta"
      foreach u in `usingfile' {
      cd "$original/folder2"
      merge 1:m id using "/`u'"

      }
      }

      Comment


      • #4
        It's difficult to help you here because:
        1) Saying "It's not working" gives no information to people that might help you. See the StataList FAQ about such matters. We need to get an exact description of how it didn't work, and how Stata responded to your syntax.

        2) Per my previous suggestion, I presume you have tried -set trace on-. That would be a good way to reveal what is going wrong with your macros. Showing us the relevant part of that would help.

        Comment

        Working...
        X