[datatable-help] New column with conditions for first and last observation by id group

Michael Smith my.r.help at gmail.com
Fri Jul 25 15:25:14 CEST 2014


This seems to work:

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]



On 07/25/2014 08:29 PM, Frank S. 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
> datatable-help at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help
> 


More information about the datatable-help mailing list