Announcement

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

  • How do I assign string a numeric range?

    Hi,

    I have a string variable "topincome" such as:
    topincome
    1
    3
    2
    4
    Each string "1", "2", "3" and "4" represents a numeric range, say, 0-5, 6-10, 11-15, and 16-20. How do I replace this string variable with their associated numeric range?

    Thanks!

  • #2
    You could do that in various ways. For most Stata purposes that would be going in quite the wrong direction. You're better off with 1 2 3 4 as values of a numeric variable and those strings as value labels.

    Code:
    . clear
    
    . input str1 topincome
    
         topincome
      1. "1"
      2. "2"
      3. "3"
      4. "4"
      5. end
    
    .
    . gen wanted = word("0-5 6-10 11-15 16-20", real(topincome))
    
    .
    . list
    
         +-------------------+
         | topinc~e   wanted |
         |-------------------|
      1. |        1      0-5 |
      2. |        2     6-10 |
      3. |        3    11-15 |
      4. |        4    16-20 |
         +-------------------+
    
    .* better idea
    
    . destring topincome, replace
    topincome: all characters numeric; replaced as byte
    
    .
    . label def topincome 1 "0-5" 2 "6-10" 3 "11-15" 4 "16-20"
    
    .
    . label val topincome topincome
    
    .
    . describe
    
    Contains data
     Observations:             4                  
        Variables:             2                  
    ------------------------------------------------------------------------------------------------
    Variable      Storage   Display    Value
        name         type    format    label      Variable label
    ------------------------------------------------------------------------------------------------
    topincome       byte    %10.0g     topincome
                                                  
    wanted          str5    %9s                  
    ------------------------------------------------------------------------------------------------
    Sorted by:
         Note: Dataset has changed since last saved.
    
    .
    . list
    
         +-------------------+
         | topinc~e   wanted |
         |-------------------|
      1. |      0-5      0-5 |
      2. |     6-10     6-10 |
      3. |    11-15    11-15 |
      4. |    16-20    16-20 |
         +-------------------+
    
    .
    .
    Last edited by Nick Cox; 04 Aug 2024, 14:10.

    Comment

    Working...
    X