Announcement

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

  • in long data, replace var1==_n with other variable by id

    Dear Listers

    I would like to replace a variable by the first occurrence of another variable.

    Code:
    input id first second
    1 50.1 50
    1 50.1 51
    1 50.1 52
    2 60.3 60
    2 60.3 61
    2 60.3 62
    end
    i want second[_n] to be replaced by first by id

    so i tryed

    Code:
    bysort id: replace second=first if second==second[_n]
    that just changed all second values to : second==first

    so i tryed

    Code:
    bysort id: replace second[_n]==first[_n]
    that gave me a weights not allowed error.

    Hope you understand what i want and can tell me how to do it.

    Lars

  • #2
    I am not clear on what you want, but

    1. _n always means "the current observation" so second and second[_n] will always be identical, regardless of whether you are using by:

    2. Subscripts can't appear before the = sign in a replace statement, so any square brackets will be thought of as an attempt to use weights, not allowed here either.

    You may want to consider whether

    Code:
    by id: gen third = first[1]
    helps you. Otherwise show a worked example of what your data will look like when done.

    Comment


    • #3
      I understand your confusion, to name the variables first and second was a bad idea.

      I want to replace the first value of B with the value of A so that the data looks like this:

      Code:
      input id A B
      1 50.1 50.1
      1 50.1 51
      1 50.1 52
      2 60.3 60.3
      2 60.3 61
      2 60.3 62
      end
      I think i figured out how to do that on the bike ride back from work.

      Code:
      input id A B C
      1 50.1 50 52.3
      1 50.1 51 52.3
      1 50.1 52 52.3
      2 60.3 60 63.3
      2 60.3 61 63.3
      2 60.3 62 63.3
      2 60.3 63 63.3
      end
      
      sort id B
      bysort id: gen seq=_n
      replace B=A if seq==1
      and if i want to change the last value of B with C

      Code:
      sort id B
      bysort id: gen last=_N
      replace B=C if last==seq
      …and they say fresh air is good for you.

      Lars


      Comment


      • #4
        Note that you don't need the extra variables. Consider (e.g.)

        Code:
        bysort id (B) : gen first = A[1]

        Comment

        Working...
        X