Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract from column Date class only in R

I have a bizarre database with all sorts of date types, such as:

datfra <- data.frame(ExactDate = c(NA, NA, NA, NA, NA),
                     DateEstimated = c("1974", "22/12/1984","<1982","year?","23/05/1981" ))

> datfra
  ExactDate DateEstimated
1        NA          1974
2        NA    22/12/1984
3        NA         <1982
4        NA          year?
5        NA    23/05/1981

Would I would like to achieve is to transfer correct dates (the ones fitting dd/mm/yyyy) to the column ExactDate and leaving the unfitting ones as NA‘s such as:

> desired_datfra 
   ExactDate DateEstimated
1       NA          1974
2 22/12/1984    22/12/1984
3       NA         <1982
4       NA          year?
5 23/05/1981    23/05/1981

Any help will be welcomed!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using as.Date and format, non-matching dates automatically get discarded.

transform(datfra, ExactDate=format(as.Date(DateEstimated, '%d/%m/%Y'), '%d/%m/%Y'))
#    ExactDate DateEstimated
# 1       <NA>          1974
# 2 22/12/1984    22/12/1984
# 3       <NA>         <1982
# 4       <NA>         year?
# 5 23/05/1981    23/05/1981
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading