Reputation: 807
So I have this very weird situation. With R and date Conversion with as.Date() function. The weirdest thing is that ifelse statement does not work as it supposed to work.
So situation:
I want to extract date from number but stuck on situations where NA occurs. If I apply as.Date(NA) I do not get any error. But weird things starts on dataFrames.
Here is example:
###### create temp data.frame
t1 <- data.frame(dateNum = c(6000,6001,NA))
##### First attempt: straight ############
t2 <- t1 %>% dplyr::mutate(
dateConverted = as.Date(dateNum)
)
##### Second attempt: ifelse statement ############
t2 <- t1 %>% mutate(
dateConverted = ifelse(is.na(dateNum),NA,as.Date(dateNum))
)
##### Third attempt: ifelse statement for number 6000 ############
t2 <- t1 %>% mutate(
naValue = is.na(dateNum),
dateFixed = ifelse(naValue,6000,dateNum),
dateConverted = ifelse(naValue,NA,as.Date(dateFixed))
)
And here is output. With errors 'origin' must be supplied
> ###### create temp data.frame
> t1 <- data.frame(dateNum = c(6000,6001,NA))
>
> ##### First attempt: straight ############
> t2 <- t1 %>% dplyr::mutate(
+ dateConverted = as.Date(dateNum)
+ ) Error in as.Date.numeric(c(6000, 6001, NA)) : 'origin' must be supplied
>
> ##### Second attempt: ifelse statement ############
> t2 <- t1 %>% mutate(
+ dateConverted = ifelse(is.na(dateNum),NA,as.Date(dateNum))
+ ) Error in as.Date.numeric(c(6000, 6001, NA)) : 'origin' must be supplied
>
> ##### Third attempt: ifelse statement for number 6000 ############
> t2 <- t1 %>% mutate(
+ naValue = is.na(dateNum),
+ dateFixed = ifelse(naValue,6000,dateNum),
+ dateConverted = ifelse(naValue,NA,as.Date(dateFixed))
+ ) Error in as.Date.numeric(c(6000, 6001, 6000)) : 'origin' must be supplied
>
Upvotes: 3
Views: 5427
Reputation: 3615
The problem is not with the NA
or with dplyr, it's with your numeric data. From ?as.Date
:
'as.Date' will accept numeric data (the number of days since an epoch), but only if 'origin' is supplied.
You're passing the function numeric values (6000 and 6001), but no information about what those represent. as.Date()
will treat these values as the number of days since an origin, but you have not provided an origin for it to calculate based on.
Upvotes: 23