6

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)    

1 Answer 1

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

or even shorter

DT[, law:=date>lawDate]

kind greetings

Sign up to request clarification or add additional context in comments.

1 Comment

Insane. I was sure there was an R-onic way to proceed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.