Announcement

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

  • Subinstr() returns "invalid syntax" within foreach loop

    Hi,

    I've tried to run this code multiple times with many adjustments, I also tried the solutions to similar problems with the subinstr() invalid syntax, but these don't seem to work. Can anyone tell me where my mistake lies?

    Code:
    local csvfiles : dir "input" files "*.csv"
    foreach file of local csvfiles {
        import delimited `"input/`file'"', clear delimiters(",") varnames(1)
        local name : subinstr("`file'", ".csv" , "", .)
        save `"output/`name'.dta"', replace
        }
    Thanks!

  • #2
    You seem to be mixing syntax from the subinstr() function (help string functions) with the syntax from the subinstr extened macro function (help extended_fcn)

    This is how you would do this with extended macro functions

    l
    Code:
    local name : subinstr local file ".csv" "", all
    This is how you would do this as a function

    Code:
    local name = subinstr(`"`file'"',".csv", "", .)
    Last edited by Maarten Buis; 27 Mar 2019, 04:52.
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Nothing to do with working in a loop. You should go

      Code:
      local name = subinstr("`file'", ".csv", "", .)

      To debug, put

      Code:
      display "`file'"
      to see what it is that you just created.
      Last edited by Nick Cox; 27 Mar 2019, 04:59.

      Comment


      • #4
        Thanks Maarten Buis Nick Cox!! I indeed mixed the syntax for the funtion and extended macro function. Another folowup question: in terms of efficiency, runs one of the two methods faster than the other, or is there not really a difference in speed?

        Comment


        • #5
          It's hard to imagine either operation taking up any appreciable time, but I am no expert at what happens at machine level.

          Comment


          • #6
            I ran the funtion within a loop which goes trough 25 datafiles with an average of 70 variables and 250 000 entries so it took a few minutes... Hence my question

            Comment

            Working...
            X