flo*_*del 12 r date read.table
在读取文件时,该read.table函数用于type.convert区分逻辑,整数,数字,复数或因子列,并相应地存储它们.
我想在混合中添加日期,以便包含日期的列可以自动识别并解析为Date对象.只应识别几种日期格式,例如
date.formats <- c("%m/%d/%Y", "%Y/%m/%d")
这是一个例子:
fh <- textConnection(
 "num  char date-format1  date-format2  not-all-dates  not-same-formats
   10     a     1/1/2013    2013/01/01     2013/01/01          1/1/2013
   20     b     2/1/2013    2013/02/01              a        2013/02/01 
   30     c     3/1/2013            NA              b          3/1/2013"
)
和输出
dat <- my.read.table(fh, header = TRUE, stringsAsFactors = FALSE,
                     date.formats = date.formats)
sapply(dat, class)
会给:
num              => numeric
char             => character
date-format1     => Date
date-format2     => Date
not-all-dates    => character
not-same-formats => character   # not a typo: date format must be consistent
在我从头开始实现它之前,包装中是否已经提供了类似的功能?或者也许有人已经给了它一个破解(或意志),并愿意在这里分享他的代码?谢谢.
我在这里快速拼凑了一个。它没有正确处理最后一列,因为该as.Date函数不够严格(as.Date("1/1/2013", "%Y/%m/%d")例如,请参阅解析正常......)
my.read.table <- function(..., date.formats = c("%m/%d/%Y", "%Y/%m/%d")) {
   dat <- read.table(...)
   for (col.idx in seq_len(ncol(dat))) {
      x <- dat[, col.idx]
      if(!is.character(x) | is.factor(x)) next
      if (all(is.na(x))) next
      for (f in date.formats) {
         d <- as.Date(as.character(x), f)
         if (any(is.na(d[!is.na(x)]))) next
         dat[, col.idx] <- d         
      }
   }
   dat
}
dat <- my.read.table(fh, header = TRUE, stringsAsFactors = FALSE)
as.data.frame(sapply(dat, class))
#                  sapply(dat, class)
# num                         integer
# char                      character
# date.format1                   Date
# date.format2                   Date
# not.all.dates             character
# not.same.formats               Date
as.Date如果您知道一种比(参见上面的示例)更严格的格式解析日期的方法,请告诉我。
编辑:为了使日期解析超级严格,我可以添加
if (!identical(x, format(d, f))) next
为了让它工作,我需要所有输入日期在需要的地方有前导零,即01/01/2013而不是1/1/2013。如果这是标准方式,我可以忍受。