Announcement

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

  • Insert comma in string variable

    Hi,

    I have a numeric variable that I would like to convert into a string variable with commas separating thousands.
    I have tried:

    tostring n, g(n_string) format(%4.0fc)

    but that gives me a string that is identical to the numeric variable:
    n n_string
    61467 61467
    1118 1118
    1499 1499
    68 68
    1291 1291
    1381 1381
    and I would like this:
    n n_string
    61467 61,467
    1118 1,118
    1499 1,499
    68 68
    1291 1,291
    1381 1,381
    Do you know how I get a string variable with commas?

    Thank you in advance.
    /Amalie
    Last edited by Amalie Timmermann; 20 May 2021, 07:30.

  • #2
    One way

    Code:
    gen n_string = string(n, "%10.0fc")

    Comment


    • #3
      See this thread here: https://www.statalist.org/forums/for...sand-separator

      Comment


      • #4
        Justin showed you how to do exactly what you are asking for.

        My point was more that you do not really want to do, what you are saying, but rather, you want to keep your variables as numbers as they are now, but control how Stata shows them to you, with a format such as the one Justine showed:

        Code:
        format var %10.0fc

        Comment


        • #5
          Perfect. Thankyou very much!

          In this case I needed the new variable because I had to make a label for a graph:

          gen studylabel = Firstauthor if y1==1
          replace studylabel = studylabel + ", " if y1==1 & (Gender !="" | Population_name != "")
          replace studylabel = studylabel + Gender if Gender != ""
          replace studylabel = studylabel + Population_name if Population_name != ""
          replace studylabel = studylabel + " (n=" + n_string + ")" if n !=.
          replace studylabel = studylabel + " (n not given)" if n ==.

          sort order
          g study = _n
          labmask study, values (studylabel)

          graph hbar AAday, ///
          over (MeanP502) bar(1, color(black)) bar(2, color(gs8)) ///
          over(study, label(labsize(tiny))) ///
          over(country, label(labsize(vsmall)))


          There might be a smarter way to make the label, but Justin's answer made this version work

          Comment

          Working...
          X