Checking if date is blank in R? -


an easy 1 sure knows how this...

in r, looking is.blank error trap in function user can specify date or can blank , default use today's date (i.e. sys.date())

i tried

date.end <- ""  # in function   if (date.end == "" || is.null(date.end)) {   message("end date not specified , setting today")   date.end <- sys.date() } else {   # use date.end passed in date class } 

but check freaks out chartodate(), i.e.

test.end == "" error in chartodate(x) :    character string not in standard unambiguous format 

please advise how 1 check blank dates in base r? (and other wisdom error trapping dates...)

adding clarify:

  1. most times function dates, e.g.

    date.end <-  as.date("31/03/2015", "%d/%m/%y") 

    so not want change class.

  2. however, how handle odd case want default today if user not specify date?

be aware sys.date() returns object of date class. see class(sys.date()). hence == comparison not make sense comparing character date.

one way solve problem convert date character:

date.end <- ""  # in function   if (date.end == "" || is.null(date.end)) {   message("end date not specified , setting today")   date.end = as.character(sys.date()) } ##end date not specified , setting today  date.end == "" ##[1] false  print(date.end) ##[1] "2015-04-01" 

note date.end character.

please see discussion in in post.

edit: complete overhaul. ok, reading follow-up comments , questions appears want following (although it's still not quite clear).

i think you're making more complicated is. first, let's make function can handle single (i) date, (ii) perhaps ill-formatted character, or (iii) null object.

datehandler <- function(x) {   if (is.null(x) || identical(x, "")) {     out <- sys.date()   } else {     x <- as.character(x)     out <- as.date(x, format = "%y-%m-%d")     if (is.na(out)) {       out <- sys.date()     }   }   return(out) }  # let's test in number of examples: datehandler("2014-02-21") datehandler(null) datehandler("21/03/1999") # wrong format, returns today datehandler("") datehandler("2014-04-01") datehandler(sys.date()) 

now, let's make function applies datehandler on list of dates:

handlelistofdates <- function(list.of.dates) {   return(do.call(c, lapply(list.of.dates, datehandler))) }  # let's test that: test.data.list <- list("2014-05-01", null, "", sys.date(),                         "2015-02-02", "1999-12-31", "") #print(test.data.list)  # see  handlelistofdates(test.data.list) # [1] "2014-05-01" "2015-04-01" "2015-04-01" "2015-04-01" "2015-02-02" "1999-12-31" "2015-04-01" 

the function handlelistofdates correctly handle vector instead of list of dates. hope want.


Comments

Popular posts from this blog

How can we post XML strings along with text strings in iOS -

How to run C# code using mono without Xamarin in Android? -

c# - cefsharp app remember password option -