Ask Your Question
2

How can a new column be created in data.table R with mutations based on specific conditions involving the date interval and other variables?

asked 2021-04-22 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-11-08 18:00:00 +0000

pufferfish gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-22 11:00:00 +0000

Seen: 17 times

Last updated: Nov 08 '22