time series - R function that looks through previous dates -


I have some weekly data slices with names, dates and ranks.

When they are two consecutive or more places in two previous periods, then you want to create a new column for the flag.

  names & lt; - c ("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "c" ) Date & lt; - c ("2015-01-19", "2014-01-12", "2014-01-05", "2014-01-01", "2015-01-19", "2014-01-12" , "2014-01-05", "2014-01-01", "2015-01-19", "2014-01-12", "2014 -01-05", "2014-01-01") Rank & Lt; - c (1,2,1,3, 2,3,2,1, 3,1,3,2) df & lt; -data.frame (name, date, rank) df & lt; -arrange (df, date, desc (rank)) df name date rank one 2014-01-01 3c 2014-01-01 2b 2014-01-01 1 c 2014-01-2 05 3b 2014-01-05 2A 2014-01-05 1B 2014-01-12 3A 2014-01-12 2C 2014-01-12 1 c 2015-01-19 3B 2015-01-19 2A 2015-01-19 1 For example: for 1 January, it was in 1st place and it was placed in less than two places on January 12 and January 5, so flag it on 1 January for 1B, it will be 2 places But it was both on previous dates, and less than 2 ore, the flag with a 0. For C, on January 1, it was no less than 2 space, hence the flag with 0.  

Here is the output I want to see:

  Date Range Coordinated One 1/1/2014 3 NA C 1/1/2014 2 NA B 1/1 / 2014 1 NCC 1/5/2014 3 NA B. 1/5/2014 2 NA No 1 / 5/2014 1 NBB 1/12/2014 3 0 One 1/12/2014 2C C 1/12/2014 1 C 1/19/2015 3 B1 1/1/2015 2 0A 1/1/2011 1 1  

Thank you very much!

I have a data.table based solution:

< Pre> Library (Data Eligible) Settte (D) [, Compatible: = Rank & lt; 3 & amp; C (NA, rank [-n]) & lt; 3 & amp; C (NA, NA, rank [-C (N-1, N.)]) & Lt; 3, name] D # name date rank corresponding # 1: one 2014-01-01 3 incorrect # 2: C 2014-01-01 2 NA # 3: B 2014-01-01 1 NA # 4: C 2014-01 -05 3 FALSE # 5: B 2014-01-05 2 NA # 6: One 2014-01-05 1 FALSE # 7: B 2014-01-12 3 Wrong # 8: One 2014-01-12 2 Wrong # 9 : C 2014-01-12 1 Incorrect # 10: C 2015-01-19 False # 11: B 2015-01 -19 2 FALSE # 12: A 2015-01-19 1 True

This sample does not produce the compatible columns exactly as the output, but it creates the task to flag the requested rows.

UPDATE

Here is an updated solution that produces output in OP with one:

  Set DT (D) [, Compatible: = Rows (CBID & Rank (lt; 3, c (NA, rank [-n]) <3, c (NA, NA, rank [-C (N-1, N)]))))% /% 3, Name] Print (D) # Name Date Rank Ent # 1: One 2014-01-01 3 NA # 2: C 2014-01-01 2 NA # 3: B 2014-01-01 1 NA # 4: C 2014-01-05 3 NA # 5: B 2014 -01-05 2 NA # 6: A 2014-01-05 1 NA # 7: B 2014 -01-12 3 0 # 8: A 2014-01-12 2 9: C: 2014-01-12 1 0 # 10: C 2015-01-19 3 0 # 11: B 2015-01-19 2 0 # 12: A 2015-01-19 1 1  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -