i having issue dates in r.
i have data dates, however, format not consistent. depending on day of month stored dmmyyyy or ddmmyyyy. fix wrote small function (see below) takes string, checks length, reformats , returns date. use sapply(dates, formatdate) , according print outs works expected. resultant vector not contain same values.
head(dates) 10651 11566 15493 13727 15920 15617
i not sure happening here, insights?
formatdate <- function(x){ print(paste("entering format date ", x)) if (nchar(x) == 8){ print(paste("nchar = ", nchar(x))) day <- substr(x, 1, 2) month <- substr(x, 3, 4) year <- substr(x, 5, 8) print(paste("day = ", day, " month = ", month, " year = ", year)) x <- paste(year,"-",month,"-",day, sep = "") print(paste("date = ", x)) x <- as.date(x, format = "%y-%m-%d") }else if (nchar(x) == 7){ day <- substr(x, 1, 1) day <- format(day, digits = 2) day <- gsub(" ", 0, day) month <- substr(x, 2, 3) year <- substr(x, 4, 7) x <- paste(year,"-",month,"-",day, sep = "") x <- as.date(x, format = "%y-%m-%d") } else { x <- na } print(paste("returning", x)) flush.console() return(x) }
this looks way complicated. if understand correctly, can this:
x <- c("1072015", "11072015") as.date(formatc(as.integer(x), width = 8, flag = 0), format = "%d%m%y") #[1] "2015-07-01" "2015-07-11"
Comments
Post a Comment