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.
Aucun commentaire:
Enregistrer un commentaire