vendredi 26 février 2016

R dplyr mutate does not work with as.Date(NA) 'origin' must be supplied

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

Aucun commentaire:

Enregistrer un commentaire