Announcement

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

  • Changing Type of Local Variables

    I have an imported dataset where I need to rename all of the variables and want to use the imported label as a part of the new name of the variables. The general idea of what I want to do is the following:

    foreach var of varlist _all {
    local varlabel : variable label `var'
    local strN = "str" + `varlabel'
    rename `var' `strN', if...

    However, 'varlabel' is a number for each variable and so does not concactenate as it is an integer. To my knowledge Tostring would not work in this situation, and if it does I have been unable to figure out how. Any help on how to change the type of a local variable would be much appreciated. I've been scouring the internet for the past couple of hours to no success.

  • #2
    Your third command wants to evaluate an expression that concatenates two strings. But in this context `var' is not a string - it is just a sequence of characters that need to be enclosed in quotation marks to make it a string constant in the expression. Consider the following examples, and note that when the local macro var contains letters rather than digits, Stata tries to interpret it as a variable name, again because it is not enclosed in quotation marks.
    Code:
    . local num 42
    
    . local str = "the number is " + `num'
    type mismatch
    r(109);
    
    . local num xx
    
    . local str = "the number is " + `num'
    xx not found
    r(111);
    
    . local num 42
    
    . local str = "the number is " + "`num'"
    
    . display "`str'"
    the number is 42

    Comment


    • #3
      Strictly speaking, all local macros contain strings. (Regardless of any terminology outside Stata, local or global macros are not considered to be variables in Stata.)

      But strings can include numeric characters. We often use the numeric interpretation of such macros.

      As William Lisowski implies, the problem here is not in what local macros can hold. The problem is in the right-hand side of your expressions.

      number1 + number2

      will be evaluated as a number (addition)

      and

      "string1" + "string2"

      will be evaluated as a string (concatenation) but mixes of type aren't allowed. Without the double quotation marks, what you supplied was too much of a puzzle.

      Note that something like this works and is not an exception.

      Code:
      . scalar frog = "toad"
      
      . local puzzle  = frog + "s"
      
      di "`puzzle'"
      toads
      it's fine for the name of a string scalar or variable to appear in an expression.
      Last edited by Nick Cox; 07 Mar 2019, 07:01.

      Comment


      • #4
        Thank you very much for the explanations, that makes sense.

        Comment

        Working...
        X