Mostafa90
Mostafa90

Reputation: 1706

Changing date with a loop vector in R

I'm facing a problem with a date vector where I want to change date format I tried many things but doesn't seem to work

Lets take an example :

library(stringr)
library(lubridate)
x <- c(NA, "40695", "40940", "01/03/2013", NA, "01/06/2011", NA, "40725",
      "01/07/2011", NA)

I tried to do it with replace function :

x <- replace(x, str_length(x) == 5, as.Date(x, "1899-12-30"))
x <- replace(x, str_length(x) == 10, as.Date(parse_date_time(x,"dmy")))

With for loop and ifelse :

for (i in seq_along(x)){

  ifelse(str_length(x[i]) == 5, 
         x[i] <- as.Date(x[i], "1899-12-30"),
         ifelse(str_length(x[i]) == 10,
                x[i] <- as.Date(parse_date_time(x[i],"dmy"))), "pas de donnees")

}

With base R :

x[str_length(x) == 5] <- as.Date(x, "1899-12-30")

I get the following error

Error in x[str_length(x) == 5] <- as.Date(x, "1899-12-30") : NAs are not allowed in subscripted assignments

Thanks

Upvotes: 2

Views: 183

Answers (1)

Remko Duursma
Remko Duursma

Reputation: 2821

Use which to drop NAs when indexing. Also, prepare an empty vector with Date-NAs, since replacing the original values does not work (you are trying to replace character with Date in a vector).

This works (base)

# empty vector with Date-class NA
z <- rep(as.Date(NA), length(x))

z[which(nchar(x) == 5)] <- as.Date(as.numeric(x[which(nchar(x) == 5)]), 
                                    origin="1899-12-30")

z[which(nchar(x) == 10)] <- as.Date(x[which(nchar(x) == 10)], 
                                    format="%d/%m/%Y")

Upvotes: 2

Related Questions