Announcement

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

  • Extract value of a variable and insert into string variable in the same observation

    Dear Statalisters

    For an example dataset like so

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(teacher students) str42 statement
    1  50 ""
    2 100 ""
    end

    I want to extract the value of variable "students" and insert it into a string variable "statement" something like below

    command
    replace statement = "This Teacher has `=students[_n]' students in her class"
    (2 real changes made)


    But rather than getting the respective values I am getting the value of the first observation in both first and second obs.
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(teacher students) str42 statement
    1  50 "This Teacher has  50 students in her class"
    2 100 "This teacher has  50 students in her class"
    end

    On the other hand I want to get
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(teacher students) str43 statement
    1  50 "This Teacher has  50 students in her class"
    2 100 "This Teacher has 100 students in her class"
    end
    Thanks in advance for any help.

  • #2
    Code:
    gen statement = "This teacher has " + string(students)+ " students in her class"

    Comment


    • #3
      Thanks a lot Andrew !

      Also just for my knowledge referencing the way I was doing is illegal and defaults to the first obs .. right ?

      regards

      Comment


      • #4
        There was nothing illegal about what you did -- that would have entailed an error message -- just that it wasn't what you wanted.

        References within commands to local macros and to items with local macro personas are always interpreted just once and before any calculations take place. They won't be interpreted according to the values in each observation. As you say, Stata when faced with a reference of this kind will use the value in the first observation.

        Comment


        • #5
          thanks Nick, much appreciated.
          kind regards

          Comment

          Working...
          X