Reputation: 585
The variable Recence_Connexion_Jrs
is composed of "NA" and some figures (from 1 to 100), and I'm trying to make the "NA" equal to "No Open", and also cut the figures into 3 groups, and the labels of the groups are in the type of string.
For example:
Recence_Connexion_Jrs Connexion
NA No open
NA No open
NA No open
1 connexion 0-7
10 connexion 7-30
The code that I used:
setDT(newdata)[!duplicated(newdata),Connexion:=ifelse(is.na(Recence_Connexion_jrs),
"No Open",cut(Recence_Connexion_jrs,breaks=c(-Inf,7,30,+Inf),
labels=c("connexion 0-7","connexion 7-30","connexion 30+")))]
But it gave the wrong result.
How can I solve that?
Upvotes: 1
Views: 59
Reputation: 193687
I would suggest doing this in two steps: (1) using cut
as you've done, and (2) using replace
for the NA
values.
Here's an example on a vector. No reason you can't do something similar in data.table
:
set.seed(123)
vec <- sample(c(1:40, NA), 100, TRUE)
new <- cut(vec, c(-Inf, 7, 30, +Inf),
labels=c("connexion 0-7", "connexion 7-30", "connexion 30+"))
new <- replace(as.character(new), is.na(new), "No open")
Or, on a small data.table
for you to see more easily:
library(data.table)
DT <- data.table(vec = c(1, NA, 8, 20, NA, 32))
DT[, new := as.character(
cut(vec, c(-Inf, 7, 30, +Inf),
labels = c("connexion 0-7", "connexion 7-30", "connexion 30+")))][
, new := replace(new, is.na(new), "No open")
][]
# vec new
# 1: 1 connexion 0-7
# 2: NA No open
# 3: 8 connexion 7-30
# 4: 20 connexion 7-30
# 5: NA No open
# 6: 32 connexion 30+
Upvotes: 3