0

I am trying to extract the date as yyyy-mm-dd (2008-12-30) using R. So, only the year, month and day.

My original date in my data looks like this "2008-12-30 00:00:00.0000000".

I have tried below:

dfs$date<-as.POSIXct(dfs$date, format="%Y-%m-%d")

dfs$date <-as.Date(dfs$date, format="%Y-%m-%d")

both two returned null for 10% of the original dates in my data, but the rest 90% seemed to be right.

I would really appreciate any suggestion to fix this!

r2evans
  • 141,215
  • 6
  • 77
  • 149
S1900
  • 1
  • Please check the 10% of the dates. It must be different format. For me `as.Date` works fine `str1 <- "2008-12-30 00:00:00.0000000." > as.Date(str1, "%Y-%m-%d")# [1] "2008-12-30"` – akrun Jul 17 '18 at 15:08
  • 1
    If you have known examples where it does not work, please make this question more [reproducible](https://stackoverflow.com/questions/5963269/) by including those examples. – r2evans Jul 17 '18 at 15:10
  • 1
    @akrun Thank you!! realized that have some "//NAs" in my data which was causing the converting date type problems – S1900 Jul 24 '18 at 20:35

1 Answers1

0

If you original source data is just text, you might be able to use substr here:

x <- "2008-12-30 00:00:00.0000000."
substr(x, 1, 10)
[1] "2008-12-30"

# or
as.Date(substr(x, 1, 10))

If some of your data does have problems, the above suggestion might get around that problem, assuming every row does in fact start with a 10 character date string.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360