How to create a dynamic counter group by patid

Hello, Dear all:
I am trying to create a dynamic counter within each patid. bascially I am trying to convert SAS retain function(carry over the previous value to current). And I read many article, it says, R won't do that. What I want to do is:

By patid
The first row, n_rec=1;
The rest of rows, if v1!=lag(v2), then n_rec=lag(n_rec)+1;
otherwise n_rec=lag(n_rec)

So each of n_rec depends on previous(n_rec). R gives me the error: can't find n_rec object.

If there is anyway to solve the problem?
Thanks a lot!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.