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...@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 ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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.