Announcement

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

  • Can't rename variable to macro

    Hi all,

    I'm trying to run the following code where I try renaming a variable to a macro but it keeps failing.

    foreach test in $Tests {

    use "$crosswalk_path" if lcd == "`test'", clear
    local testname = test[1]

    capture noisily {
    use "$data_extract_dir/`test'.dta", clear
    merge m:1 msa date using "$data_extract_dir/Data.dta", ///

    preserve
    rename result `testname'
    restore
    }
    }

    The error message I keep getting is Syntax is rename oldname newname [, renumber[(#)] addnumber[(#)] sort ...] rename (oldnames) (newnames) [, renumber[(#)] addnumber[(#)] sort ...] rename oldnames , {upper|lower|proper}.

    Can anyone help me fix this?

  • #2
    You need to tell us what is inside test[1]

    The implication of the error message is that it's not a legal new variable name.

    Comment


    • #3
      Originally posted by Nick Cox View Post
      You need to tell us what is inside test[1]

      The implication of the error message is that it's not a legal new variable name.
      test[1] contains the name of the test - for instance "Blood Test 1".

      I suppose I figured out the problem - you can't rename a variable to one with spaces (such as "Blood Test 1"), which is why I am getting the error message, correct?

      The problem is that I want to run individual regressions for each of these tests inside the loop and output them to a table with the test names using eststo. I thought the best way to do that would be to rename the dependent variables to the names of the tests, otherwise I just get an output table of 100 regressions with no way to identify which is which.

      Any way to get around this?

      Comment


      • #4
        Absolutely.

        "Blood Test 1" is not a legal variable name. in Stata names may not contain spaces. It could be a variable label.

        Alternatively if you push it through strtoname() then you'll get a suitable name. You need to do that before calling up rename.

        Code:
        . display strtoname("Blood Test 1")
        Blood_Test_1
        eststo (most up to date version is from SSC, as you are asked to explain: FAQ Advice #12) is a wonderful command I never use. It probably has a hook to use variable labels, and if it does then the variable label solution is preferable. That could be

        Code:
        label var result "`testname'" 

        or (cutting out the unnecessary macro)

        Code:
        label var result "`= test[1]'" 
        That said, if you are storing metadata in variables, that is likely to be problematic. but we can't tell for sure without a data example.

        Comment

        Working...
        X