Search code examples
for-loopforeachdirectorystatalocal

How to loop through a folder with conditional statement in Stata?


I have a folder with a bunch of csv files and I want to loop through each file, check if a list of variables in each of the files = 0, then save the csv file as a .dta if they do not equal 0.

I'm having trouble finding online help to do this but here's what I've tried so far:

foreach file in `files' {
  import delimited using `file', clear
  if a & b & c & d != 0 
  save "Desktop\myfolder\`file'.dta"
}

when I try this though Stata tells me "{ required r(100)".

Any help appreciated. Thanks.


Solution

  • Stealing some code from the estimable @Wouter Wakker, let's first suppose that the criterion is that a non-zero value is found somewhere in a b c d

    foreach file in `files' {
        import delimited using `file', clear
    
        local OK = 0 
    
        quietly foreach v in a b c d { 
            count if `v' != 0 
            if r(N) > 0 local OK = 1 
        } 
    
        if `OK' save "Desktop/myfolder/`file'.dta"
     
    }
    

    Whatever your precise criterion, I think you need to loop over a b c d and (say) count or summarize according to what you want or do not want.