[datatable-help] Subsetting a data table and add a new column in one step

Michael Smith my.r.help at gmail.com
Wed Jul 23 14:46:02 CEST 2014


This gives the output in your example:

DT <- DT[start <= "2010-01-01"]
DT[, age := round((as.Date("2010-01-01") - DT$born) / 365.25, 1)][]

Alternatively you could also do it like this (but it might be less
efficient on a larger dataset since it first does the calculation and
then the subsetting; however, the date calculation in this example
should scale well in any case):

DT[, age := round((as.Date("2010-01-01") - DT$born) / 365.25, 1)][
  start <= "2010-01-01"]



On 07/22/2014 10:49 PM, Frank S. wrote:
> Hello everyone.  I’ve the following data table:
> 
>  
> 
> DT <- data.table(id=1:5,
> 
>                
> born=as.Date(c("1939-10-28","1943-02-26","1946-03-09","1947-05-19","1932-04-03")),
> 
>                
> start=as.Date(c("2012-01-01","1980-07-15","1998-10-28","2011-10-28","2010-10-28")),
> 
>                
> end=as.Date(c("2012-05-01","2014-02-01","2012-10-20","2013-10-15","2012-08-25")))
> 
>>DT
> 
>    id       born      start        end
> 
> 1:  1 1939-10-28 2012-01-01 2012-05-01
> 
> 2:  2 1943-02-26 1980-07-15 2014-02-01
> 
> 3:  3 1946-03-09 1998-10-28 2012-10-20
> 
> 4:  4 1947-05-19 2011-10-28 2013-10-15
> 
> 5:  5 1932-04-03 2010-10-28 2012-08-25
> 
> I would like to be able to keep only those subjects whose “start” date
>  is previous to “2010-01-01” date, and then calculate
> 
> the age they were at 2010-01-01 in a newDT:
> 
>  
> 
>    id       born      start        end    age
> 
> 2:  2 1943-02-26 1980-07-15 2014-02-01    66.8
> 
> 3:  3 1946-03-09 1998-10-28 2012-10-20    63.8
> 
>  
> 
> I have:
> 
>  
> 
> newDT <- DT[, if(start <= as.Date("2010-01-01")) {
> 
> list(c(id, born, start, end, age=unclass(round(difftime(Apertura,
> born)/365.25,1))))
> 
> } ,
> 
> by=c('id','born','start','end')]
> 
>  
> 
> But it appears an error message!  Can anyone please help me with this?
> Thank you!
> 
>  
> 
>  
> 
> 
> 
> _______________________________________________
> 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