Announcement

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

  • Replace a value in one variable with a single value from another variable using a conditional statement

    Hi everyone,

    I would like to assign the value/s of one variable to a different variable for a different ID.

    For example, I would like the newly created variable test to equal the sum of variable1 values for IDs #4 and #22 on ID #13.

    Something like:

    gen test=0
    replace test= variable1[id==4]+variable1[id==22] if id==13

    A workaround would be to create new variables where values for all records for that variable is the value/s of interest (example below) but I was hoping there might be a more simple approach.

    gen test = 0

    gen variable2 = variable1 if id==4
    egen variable3=max(variable2)

    gen variable4 = variable1 if id==22
    egen variable5 = max(variable4)

    replace test = variable3+variable5 if id==13

    Thanks very much!

  • #2
    This seems a little bizarre without context, but

    Code:
    summarize variable1 if inlist(id, 4, 22), meanonly 
    gen test = cond(id == 13, r(sum), 0)
    is more direct. The option name meanonly is misleading; even with that minimal option, much more is calculated than just the mean.

    With your route, there is much unneeded copying and putting constants into variables.

    Do you have any or even many more of such manipulations? If so, there is likely to be a more systematic approach.

    Comment


    • #3
      Thanks Nick, that's much more efficient.

      This is only required in a few places so no need for a more systematic approach.

      Much appreciated!

      Comment

      Working...
      X