r - 检查 R 中的日期是否为空?

标签 r date testing

很简单,但我相信有人知道怎么做...

在 R 中,我一直在寻找类似 is.blank 的东西来在我的函数中进行错误陷阱,用户可以在其中指定一个日期或者它可以是空白,我们将默认使用今天的日期(即 Sys.Date())

我试过了

date.end <- ""

# then in function  
if (date.end == "" || is.null(date.end)) {
  message("end date not specified and so setting to today")
  date.end <- Sys.Date()
} else {
  # use the date.end passed in as Date class
}

但是这个检查让 charToDate() 变得异常,即

test.end == ""
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

请指教如何检查 base R 中的空白日期? (以及错误捕获日期的任何其他智慧......)

添加以澄清:

  1. 大多数时候该函数会得到很好的日期,例如

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

    所以我不想换课。

  2. 但是,如果用户没有指定日期,您如何处理您想默认为今天的奇怪情况?

最佳答案

请注意 Sys.Date() 返回一个 Date 类的对象。请参见 class(Sys.Date())。因此,当您将 characterDate 进行比较时,== 比较没有意义。

解决问题的一种方法是将 Date 转换为 character:

date.end <- ""

# then in function  
if (date.end == "" || is.null(date.end)) {
  message("end date not specified and so setting to today")
  date.end = as.character(Sys.Date())
}
##end date not specified and so setting to today

date.end == ""
##[1] FALSE

print(date.end)
##[1] "2015-04-01"

请注意,date.end 现在是一个字符

请参阅 in this post. 中的讨论

编辑:完成大修。好的,通过阅读您的后续评论和问题,您似乎想要以下内容(尽管仍然不太清楚)。

我认为你让事情变得比实际情况更复杂。首先,让我们创建一个函数来处理单个 (i) Date,(ii) 可能格式不正确的字符,或 (iii ) NULL 对象。

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 it in a 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())

现在,让我们创建一个在日期列表上应用 dateHandler 的函数:

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 this

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"

handleListOfDates 函数也将正确处理 vector 而不是 list 日期。 希望这就是您想要的。

关于r - 检查 R 中的日期是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392675/

相关文章:

r - tsne 初始 PCA 步骤在做什么

r - 修改 ggplot 中的 viridis 调色板

swift - 你如何以这种格式显示日期? "Jul 18, 2018 at 10:02 AM"

java - 将日期转换为全文

ios - 在为 IOS 发布之前如何查看我的应用程序页面?

python - 在 Nose 测试类中定义的固定装置是否在函数之间被调用?

javascript - Jest.fn - 使用 jest.mock 时返回值返回未定义

R 在 for 循环中使用 tryCatch 将带有错误值的行添加到输出

r - 使用数据库时 dplyr 加入 : How do you do a non standard join `col1` ! = `col2`?

java - 在 Java 中解析日期?