Announcement

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

  • Renaming each variable label as a substring of old label

    I have a set of variables v1 through v154 that I want to relabel by excluding the first 16 characters of the original label. The following code expresses what I want to do, but it is not in proper syntax since you cannot use the substr() function in the label variable command.
    foreach x of varlist v1-v154 {
    local varlabel : var label `x'
    label variable `x' substr("`varlabel'",17,.)
    }

    How do I achieve my task?

  • #2
    Code:
    foreach x of varlist v1-v154 {
        local varlabel : var label `x'
        label variable `x' "`=substr("`varlabel'",17,.)'"
    }
    Last edited by Hemanshu Kumar; 08 Sep 2022, 13:58.

    Comment


    • #3
      Thank you Hemanshu. Can you provide intuition for why there needs to be an equal sign in front of substr()?

      Comment


      • #4
        The syntax is
        Code:
         label variable varname ["label"]
        So Stata is going to read the part after the variable name as the literal string substr("`varlabel'",17,.) (after substituting in the content of the varlabel macro, of course). This is not what you want; you want the substr() function to be evaluated. That necessitates the `=...'

        Comment


        • #5
          Re #3. The -label var- command expects a literal string as its final argument. By itself substr(whatever) is not a literal string: it is an expression using a Stata function that if evaluated will be a literal string. The `=any_expression' syntax is Stata macro-speak for: evaluate the expression and replace this by the result of that evaluation.

          Added: Crossed with #4.
          Last edited by Clyde Schechter; 08 Sep 2022, 14:25.

          Comment


          • #6
            More broadly, the `=<exp>' syntax indicates that you would like whatever expression is in between those delimiters to be evaluated in-line and have the result substituted. So:

            Code:
             label variable `x' "`=substr("`varlabel'",17,.)'"
            Is functionally equivalent to:

            Code:
            local expression = substr("`varlabel'",17,.)
            label variable `x' "`expression'"
            The only difference is that in the former instance, the expression is evaluated in-line and in the latter instance the expression is first assigned to a local macro.

            For more information, see: pmacro.pdf (stata.com), specifically page 14 on "Macro expansion operators and function."

            Edit: Crossed with #5
            Last edited by Ali Atia; 08 Sep 2022, 14:32.

            Comment

            Working...
            X