Announcement

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

  • recast and replace data

    I have a variable with the type of byte and would like to recast to string, so that I can replace the numbers with a String.
    Code:
    . But when I try to recast it, it shows invalid.
    
    describe ID
    
                  storage   display    value
    variable name   type    format     label      variable label
    ------------------------------------------------------------------------
    ID        byte    %10.0g                
    
    recast str10 ID
    
    ID:  str16 invalid
    r(109);

  • #2
    You need to go one step beyond the on-line help to the manual entry to find the key information:

    Note that recast is not a command to change, or to map, string variables to numeric variables
    or numeric variables to string variables. For that, one of encode, decode, destring, or tostring
    is likely to be appropriate.
    If you need a string variable here, the command to use will be decode if value labels are defined; otherwise it will be tostring.

    Comment


    • #3
      Thanks Nick! I've successfully replaced the number with strings. However, some errors happened when I was trying to loop it:

      it works when:
      Code:
      tostring ID, replace
      
      replace ID = "A1" if ID == "1"
      replace ID = "A2" if ID == "2"
      replace ID = "A3" if ID == "3"
      But it does not work when I try to loop it:
      Code:
      input str2 NumList
      1
      2
      3
      end
      levelsof NumList, local(NumList) 
      
      foreach x of local NumList {
      replace ID = A`x' if ID == `x'
      }

      Comment


      • #4
        ID is a string, so you need to enclose its values in double quotes:

        Code:
        replace ID = "A`x'" if ID == "`x'"

        Comment

        Working...
        X