Announcement

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

  • Replacing values

    Hi all,

    I have a dataset containing values ranging from 1 to 3. I'd like to replace all the 1 to 3, and all the 3 to 1. But if I first run the code for replacing 1 to 3, and then run the second code to replace 3 to 1, then all the replaced 3 including the original 3 gets replaced with 1. Is there a simple code to replace only the original 1 and 3 to 3 and 1 respectively? ( I cannot change it to any other value)
    Thanks in advance.
    Last edited by Salini Kh; 03 Mar 2019, 08:54.

  • #2
    Salini:
    the following toy-example will hopefully give you some clues:
    Code:
    . set obs 2
    number of observations (_N) was 0, now 2
    
    . g id=_n
    
    . g score=_n
    
    . replace score=3 if score==2
    (1 real change made)
    
    .  recode score (1 = 3) (3 = 1), gen(new_score)
    (2 differences between score and new_score)
    
    . list
    
         +-----------------------+
         | id   score   new_sc~e |
         |-----------------------|
      1. |  1       1          3 |
      2. |  2       3          1 |
         +-----------------------+
    
    .
    Kind regards,
    Carlo
    (Stata 19.0)

    Comment


    • #3
      Thank you very much, Carlo. That worked perfectly.

      Comment


      • #4
        With nothing else said

        Code:
        replace whatever = 4 - whatever if inlist(whatever, 1, 3)
        would work too.

        In practice, this sounds like an ordered categorical variable you want to reverse, so watch out for value labels too.

        Comment

        Working...
        X