简体   繁体   English

为多个条件创建一组新值

[英]Create a new column for set of values by multiple conditions

Let's say I have a data table: 假设我有一个数据表:

> a<-data.table(col1=c(7,85,1905,22,250))
   col1
1:    7
2:   85
3: 1905
4:   22
5:  250

I would like to add a new column in the same data table, considering these conditions condition: 考虑到以下条件,我想在同一数据表中添加新列:

if col1(i) <10 then "A"
else if col1(i) <100 then "B"
else if col1(i) <1000 then "C"
else "D"

So, I'd obtain 所以,我会得到

   col1 col2
1:    7    A
2:   85    B
3: 1905    D
4:   22    B
5:  250    C

I have tried the ifelse method but it puts "A" in all columns, and doc says that this method works only on first element of the vector it uses. 我尝试了ifelse方法,但在所有列中都添加了“ A”,而doc表示该方法仅对它使用的向量的第一个元素有效。

dt[, col2 := ifelse(col1 < 10,'A','B')]

I don't want to use complex and long loops to do that so if somebody can explain how it works in R , I'd be thankful. 我不想使用复杂的长循环来做到这一点,所以如果有人可以解释它在R工作原理,我将非常感激。

Regards. 问候。

cut is a good option for you, this way you avoid using nested ifelse s cut对您来说是一个不错的选择,这样可以避免使用嵌套的ifelse s

> a[, col2:=cut(a$col1, 
                breaks=c(-Inf,10,100,1000,Inf), 
                include.lowest = TRUE, 
                labels=c("A", "B", "C", "D"))]
> a
   col1 col2
1:    7    A
2:   85    B
3: 1905    D
4:   22    B
5:  250    C

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

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