Colonel Beauvel
Colonel Beauvel

Reputation: 31181

Adding column with condition using data.table

Suppose I have the following data.table:

date=c("2014-02-06","2014-02-06","2014-03-01","2014-03-01","2014-03-28","2014-04-25","2014-04-25")
departure=c("NY", "NY", "Doha", "Tokyo", "Paris", "Tokyo", "Tokyo")
arrival=c("Milano", "Beijing", "Moscow", "Moscow", "Singapore", "Yaounde", "Milano")
DT<-data.table(date, departure, arrival)

giving this result:

         date departure   arrival
1: 2014-02-06        NY    Milano
2: 2014-02-06        NY   Beijing
3: 2014-03-01      Doha    Moscow
4: 2014-03-01     Tokyo    Moscow
5: 2014-03-28     Paris Singapore
6: 2014-04-25     Tokyo   Yaounde
7: 2014-04-25     Tokyo    Milano

Now I have this date:

lawDate="2014-03-17"

And I want to add a column named "law" in DT such as if date>lawDateit contains TRUE, FALSE otherwise. I am doing this for the moment but I do not know if it is the most efficient way ... since my table DT could be extremely big ...

My current solution ... but I do not know if there is a better way for data.table to do this ..

 DT$law = ifelse(date>lawDate, TRUE, FALSE)    

Upvotes: 6

Views: 4346

Answers (1)

Walter
Walter

Reputation: 353

DT[, law:=FALSE][date>lawDate, law:=TRUE]

or even shorter

DT[, law:=date>lawDate]

kind greetings

Upvotes: 8

Related Questions