[R] Difference in dates for unique ID

farnoosh sheikhi farnoosh_81 at yahoo.com
Sun Feb 15 19:41:12 CET 2015


That's exactly what I was thinking. Thanks tons.

Sent from Yahoo Mail on Android

From:"arun" <smartpink111 at yahoo.com>
Date:Sun, Feb 15, 2015 at 2:47 AM
Subject:Re: Difference in dates for unique ID

HI Farnoosh,



Not sure I understand the expected output.  The difference between the first 2 days is "136 days"

May be this helps

  library(data.table)
      dcast.data.table(setDT(df)[, list(Visit=.N, Diff= as.numeric(abs(diff(as.Date(Date, format='%d-%b-%y'))))) ,
        by = ID], ID+Visit~ Diff, value.var='Diff', length)

    ID Visit 136 255 857
    1:  1    2  1  0  0
    2:  2    3  0  1  1







On Wednesday, February 11, 2015 5:47 PM, farnoosh sheikhi <farnoosh_81 at yahoo.com> wrote:



Hi Arun,

I have a data set that look s like below. I wanted to get a difference in dates for each unique ID and record it as a new X and have binary input for each one. 

ID  Date
1        06-Sep-13
1        20-Jan-14
2        06-Mar-12
2        25-Jun-11
2        29-Oct-13



For example for the first two date for ID=1 ( 20-Jan-14 - 06-Sep-13 ~ 121) and I want the data to be like follow:

ID  Visit  121
1      2        1
2      3        0


I really appreciate if you can help me with this. I know I need to write some kind of loop, but I don't know how to think of the logic behind it.
Thanks a lot.



Farnoosh


	[[alternative HTML version deleted]]



More information about the R-help mailing list