Announcement

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

  • Calculator

    I am trying to add two means of two different variables without creating a new variable for example mean p1 + mean p2 , how do i do that?

  • #2
    Code:
    summarize p1, meanonly
    scalar define mean_p1 = r(mean)
    summarize p2, meanonly
    display in smcl as text "Mean of p1 + mean of p2 = " as result %10.0g r(mean) + mean_p1

    Comment


    • #3
      Joseph Coveney was 101% correct. Proper clean syntax you can put into a .do file.

      But sometimes, you just want quick and dirty. Stata can do that with display.

      Code:
      sum p1 p2
      then
      "display " (copy/paste mean1) + (copy/paste mean2)"

      This approach is *not* preferred, but if you are used to documenting everything in a .do file, a little interactive command doesn't hurt, so long as it doesn't change the data

      Comment


      • #4
        One small note about the use of scalars instead of macros: make sure that the name of the scalar is different from the variable name. Joseph Coveney chose a scalar name that was unlikely to be the same as a variable, but if there is a variable named mean_p1, the display command would have shown the value of the variable mean_p1 from the first observation instead of the desired value of the scalar. Two ways to avoid this problem:
        1. use distinctive names for scalars that you would never be used for variable names
        2. use the form scalar(name) to refer to scalars, as in: display scalar(mean_p1).
        See Gueorgui I. Kolev, 2006. "Stata tip 31: Scalar or variable? The problem of ambiguous names". Stata Journal 6(2):279-280.
        Stata/MP 14.1 (64-bit x86-64)
        Revision 19 May 2016
        Win 8.1

        Comment


        • #5
          Here's another way. The example is silly but the method is not.

          Code:
          sysuse auto, clear
          mata : mean(st_data(. , tokens("turn trunk")))
                           1             2
              +-----------------------------+
            1 |  39.64864865   13.75675676  |
              +-----------------------------+
          . mata : rowsum(mean(st_data(. , tokens("turn trunk"))))
            53.40540541

          Comment


          • #6
            Elaborating a bit on #4, another way to avoid a clash between variable names and scalar names is to use -tempname-s for scalars.

            Comment


            • #7
              I had actually initially written the post to use a tempname at first, but simplified it in order to show just the steps involved more clearly.

              Comment

              Working...
              X