Home > Software design >  Create a new column by other column's value in data table in r
Create a new column by other column's value in data table in r

Time:09-28

Lets say I have a data table like this

| x | y |
| - | - |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |

And I need to create another column z based on the value of x : if its x>=1 and x<=3 then the value should be 1 else be 0

| x | y | z |
| - | - | - |
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 1 |
| 4 | 4 | 0 |
| 5 | 5 | 0 |

I was trying to use dt[, z:= ,] But I'm not sure how to add the conditions to the function

CodePudding user response:

Use the ifelse function

dt[, z := ifelse(x >= 1 & x <= 3, 1, 0)]

Or, more directly, you can coerce the logical condition to integer--TRUE will be 1, FALSE will be 0:

dt[, z := as.integer(x >= 1 & x <= 3)]

Or using data.table's helper

  •  Tags:  
  • r
  • Related