Announcement

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

  • Using value labels in expression to modify value labels

    Hello,
    I would like to modify value labels of a variable when I know the labels but not necessarily the underlying values to which they correspond. In my case the underlying value is not important and may change, and the code should be agnostic to this. Based on Stata Tip 14: "Using value labels in expressions", I hoped something like this would work:

    label define gender "F":gender "Girls", modify

    where I expect the piece "F":gender to return the value that F is a label for, and the command as a whole would then relabel F to Girls. But this does not work and Stata complains that I'm using "invalid syntax". What am I missing or how else could this be done?

    Best regards,


    Momar


  • #2
    The solution is different, but first note that the help for label defines legal syntax:

    label define lblname # "label" [# "label"...] [, add modify replace nofix]

    With only very occasional exceptions, whatever isn't explicitly permitted is forbidden. Your fantasy syntax is illegal, as you found out.
    With this much known, there are various ways to proceed. but perhaps the easiest is

    Code:
    decode gender, gen(sex)
    replace sex = "Girls" if sex == "F"
    encode sex, gen(gender2)
    A merit of that approach is that it changes only what you see changed. Changing value labels can be tricky, as you need to watch out for side-effects.

    Although I have not used any here, many ways of looking up things are documented under help extended fcn

    For that matter, describe and label list would tell you what corresponds to what.
    Last edited by Nick Cox; 15 Aug 2014, 09:18.

    Comment


    • #3
      The key point here is the word expression. You need to evaluate that expression.

      Code:
      label define `= gender "F":gender' "Girls", modify
      should work fine.

      Also see labvalch3 as a part of labutil2 from the SSC.

      and code e.g.

      Code:
      labvalch3 gender ,subst("F" "Girls")
      Best
      Daniel

      Comment


      • #4
        Thanks both Nick and Daniel for the very pedagogical solutions!

        Comment


        • #5
          Just for posterity there is a small typo in Daniel's solution. This is what worked for me:

          label define gender `="F":gender' "Girls", modify

          Thanks again.

          Comment


          • #6
            You are right. I omitted the value label name, thanks for spotting this. Should be

            Code:
            label define lblname `= "label":lblname' "new label" ,modify


            Best
            Daniel

            Comment

            Working...
            X