Reputation: 960
I would like to convert some columns from numbers to date format; and I'm thinking about using the following code:
colList <- c("Date1","Date2")
dataDT[, (colList) := lapply(.SD, function(x){
if (x == 0) {NA}
else {as.Date(x, origin = "1900-01-01")}
}), .SDcols = colList]
Basically, if the value is 0, then use NA rather than "1900-01-01". Now the problem is:
Warning messages:
1: In if (x == 0) { :
the condition has length > 1 and only the first element will be used
Is there a way to resolve it?
Upvotes: 0
Views: 723
Reputation: 155
Use "ifelse" instead of "if" in this case:
ifelse (x == 0,NA, as.Date(x, origin = "1900-01-01"))
Upvotes: 2
Reputation: 25225
Another option is to use replace
:
dataDT[, (colList) := lapply(.SD,
function(x) as.Date(replace(x, x==0, NA), origin = "1900-01-01")),
.SDcols = colList]
Upvotes: 0