Yuva
Yuva

Reputation: 95

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.

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.

Regards.

Upvotes: 0

Views: 63

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61164

cut is a good option for you, this way you avoid using nested ifelses

> 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

Upvotes: 2

Related Questions