Announcement

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

  • Loop over files and rename variable with filename

    Hi there,

    I have multiple .dta datasets and they all contain the same variable labeled "Q". I want to loop over the datasets and rename the variable with the name of the dataset (the filename). (e.g. the variable Q in dataset eps.dta should be renamed to eps) I came up with the following code:

    Code:
    loc datasets : dir . files "*.dta"
    foreach f of local datasets {
        di as result "Reading `f'"
        use "`f'", clear
        local sheetname=subinstr("`f'",".dta")
        rename Q ("`sheetname'")
        save "`f'", replace
    }
    However, I get the error message "invalid syntax". Could somebody help me to fix my code?

    I also looked at the https://www.statalist.org/forums/for...rename-command post, if I run the code of that post I get the error message "variable Q not found". I tried with different datasets and still get the same error message.

    Thank you very much!

    Best regards,
    Jonas
    Last edited by Jonas Wessel; 12 Nov 2020, 09:25.
Working...
X