Announcement

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

  • Combining numeric variables using tostring but preserving number of digits to right of decimal point

    Hi all,
    I'm struggling with a formatting issue. I have a long list of variables and am calculating the median and interquartile range for each, and then want to display both values together in one cell with one digit to the right of the decimal for each number. I have set up a couple foreach loops to do this. Stata calculates the median and IQR in the first loop as expected. In the second loop, I have

    foreach x in varlist {
    tostring median_`x', replace
    tostring iqr_`x', replace
    gen `x'=median_`x' + " (" + iqr_`x' + ")"
    }

    No matter what numeric format I have going in to this second loop, the tostring command seems to get rid of the formatting I specified and makes the numbers formatted with as few digits as possible. For example, if I have median of 5.0 and IQR of 1.0 and want the output to look like "5.0 (1.0)", all I can get with tostring is "5(1)". I tried using format:

    foreach x in varlist {
    tostring median_`x', format (%3.1f) replace
    tostring iqr_`x', format(%3.1f) replace
    gen `x'=median_`x' + " (" + iqr_`x' + ')'
    }

    But I get the error "type mismatch" because I am trying to combine string and numeric subexpressions. Does anyone have any suggestions of how I can accomplish what I am trying to do? I've tried to search around for a way to do this by replacing a substring but I can't figure out how to do it when I am searching for the lack of something (i.e. a decimal point). Any help is much appreciated.

  • #2
    Probably the lack of double quotes. Note that once the variable is a string, you can concatenate by simply adding.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float var1
    3
    2
    1
    end
    
    l
    tostring var1, replace format("%3.1f")
    l
    gen median="("+ var1+ ")"

    Res.:


    Code:
     
    . tostring var1, replace format("%3.1f")
    var1 was float now str3
    
    . 
    . l
    
         +------+
         | var1 |
         |------|
      1. |  3.0 |
      2. |  2.0 |
      3. |  1.0 |
         +------+
    
    . 
    . gen median="("+ var1+ ")"
    
    . l
    
         +---------------+
         | var1   median |
         |---------------|
      1. |  3.0    (3.0) |
      2. |  2.0    (2.0) |
      3. |  1.0    (1.0) |
         +---------------+
    
    .
    Last edited by Andrew Musau; 20 Jun 2023, 16:54.

    Comment


    • #3
      Double quotes! Of course. Thank you Andrew!!

      Comment

      Working...
      X