I may not understand exactly what you want, because when I try to follow
your instructions, I get a different result. But, perhaps you can use this
code and modify it to suit your needs.
# number of rows
L <- dim(df)[1]
# determine for each row if it is within the first 3 months
mins <- aggregate(list(minym=df$YEAR_MTH), list(CASE_ID=df$CASE_ID), min)
df2 <- merge(df, mins)
df2$first3 <- df2$YEAR_MTH <= df2$minym + 3
# compare one row with the next, in terms of ...
# the same value for CASE_ID
samecase <- df2$CASE_ID[-L]==df2$CASE_ID[-1]
# a change in value for ATT_1
diffatt <- df2$ATT_1[-L]!=df2$ATT_1[-1]
# count
aggregate(list(No.of.changes=(df2$first3[-1] & df2$first3[-L] & samecase &
diffatt)),
list(CASE_ID=df2$CASE_ID[-L]), sum)
Jean
On Wed, Jul 30, 2014 at 2:08 AM, Abhinaba Roy <[email protected]>
wrote:
> Dear R-helpers,
>
> I want to count the number of times ATT_1 has changed in a period of 3
> months(can be 4months) from the first YEAR_MTH entry for a CASE_ID. So if
> for a CASE_ID we have data only for two distinct YEAR_MTH, then all the
> entries should be considered, otherwise only the relevant entries will be
> considered for calculation.
> E.g. if the first YEAR_MTH entry is 201304 then get the number of changes
> till 201307(inclusive), similarly if the first YEAR_MTH entry is 201302
> then get the number of changes till 201305.
>
> Dataset
> CASE_ID YEAR_MTH ATT_1
> CB26A 201302 1
> CB26A 201302 0
> CB26A 201302 0
> CB26A 201303 1
> CB26A 201303 1
> CB26A 201304 0
> CB26A 201305 1
> CB26A 201305 0
> CB26A 201306 1
> CB27A 201304 0
> CB27A 201304 0
> CB27A 201305 1
> CB27A 201306 1
> CB27A 201306 0
> CB27A 201307 0
> CB27A 201308 1
>
> The final dataset should look like
>
> ID_CASE No.of changes
> CB26A 5
> CB27A 3
>
> where 'No.of changes' refer to the change in 3 months (201302-201305 for
> CB26A and 201304-201307 for CB27A).
>
> How can this be done in R?
>
> Regards,
> Abhinaba Roy
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> [email protected] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.