简体   繁体   English

通过r中data.table中其他列的值创建一个新列

[英]Create a new column by other column's value in data table in r

Lets say I have a data.table like this假设我有一个这样的 data.table

| 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 的值创建另一列 z:如果其 x>=1 且 x<=3,则该值应为 1,否则为 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我试图使用dt[, z:=,]但我不确定如何将条件添加到 function

Use the ifelse function使用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:或者,更直接地说,您可以将逻辑条件强制转换为整数——TRUE 将为 1,FALSE 将为 0:

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

Or using data.table 's helper %between% :或者使用data.table的助手%between%

dt[, z := as.integer(x %between% c(1, 3))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM