Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can create a new column in a data.table by using the ":=" operator and providing the mutation condition within the brackets of the data.table syntax. For example, let's say we have a data.table called "dt" with variables "date", "value1", and "value2":

library(data.table)
dt <- data.table(date = as.Date(c("2021-01-01", "2021-01-05", "2021-01-10", "2021-01-15")), 
                 value1 = c(10, 20, 30, 40), 
                 value2 = c(5, 8, 11, 7))

And we want to create a new column called "value3" that has a value of 1 if the date falls within a specified interval and if the value1 is greater than 20, and 0 otherwise. We can do this using the following code:

dt[, value3 := ifelse(date >= as.Date("2021-01-05") & date <= as.Date("2021-01-10") & value1 > 20, 1, 0)]

In this code, we use the ":=" operator to create a new variable called "value3" in the data.table "dt". We then provide the mutation condition within the brackets using the ifelse statement. The condition checks whether date is within the specified interval (between January 5th and January 10th) AND whether value1 is greater than 20. If both conditions are true, then "value3" is assigned a value of 1, otherwise it is assigned a value of 0.

The resulting data.table with the new "value3" column will be:

> dt
         date value1 value2 value3
1: 2021-01-01     10      5     0
2: 2021-01-05     20      8     0
3: 2021-01-10     30     11     1
4: 2021-01-15     40      7     0