Hi Frank, Not sure about a one-liner, but this seems to do what you want:
> DT <- data.table(obs=1:7, id=c(1,1,1,4,4,4,4), time=c(3,4,7,5,8,10,15)) > DT[,value:=0] > DT[!duplicated(id),value:=2] > DT[!duplicated(id,fromLast=T),value:=1] > DT obs id time value 1: 1 1 3 2 2: 2 1 4 0 3: 3 1 7 1 4: 4 4 5 2 5: 5 4 8 0 6: 6 4 10 0 7: 7 4 15 1 Seems too straightforward, though, so maybe I am missing something about your problem. Please elaborate if so. Regards, Matt On Fri, Jul 25, 2014 at 8:29 AM, Frank S. <[email protected]> wrote: > Hi all, I'm very novice in data.table management, and I have the > following doubt about this data: > > > > > DT <- data.table(obs=1:7, id=c(1,1,1,4,4,4,4), time=c(3,4,7,5,8,10,15)) > > DT > obs id time > 1: 1 1 3 > 2: 2 1 4 > 3: 3 1 7 > 4: 4 4 5 > 5: 5 4 8 > 6: 6 4 10 > 7: 7 4 15 > > > > In general, I know that I can select respectively the first and the last > observation within "id" group with: > > > > First observation: *DT[!duplicated(id)] * > > Last observation:* DT[!duplicated(id, fromLast=T)] * > > > > But, how can I add a new column, called "value", which contains all zeros > except: > > 1) The first observation within each "id" group, which is equal to 2 > > 2) The last observation within each "id" group, which is equal to 1 ? > > > > obs id time value > 1: 1 1 3 2 > 2: 2 1 4 0 > 3: 3 1 7 1 > 4: 4 4 5 2 > 5: 5 4 8 0 > 6: 6 4 10 0 > 7: 7 4 15 1 > > > > I've tried with conditionslas, ifelse, etc, but I get an error message. > Please, can you help me? > > > > Thanks in advance!! > > > > > > > > > > > > > > > > > > > > > > > > _______________________________________________ > datatable-help mailing list > [email protected] > https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help >
_______________________________________________ datatable-help mailing list [email protected] https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help
