使用unlist将日期型数据的列表转换为向量时,出现的异常

在使用unlist函数,将日期型的列表,转换为向量时,不会得到期望的结果,如下:

> dateLst <- list(Sys.Date())
> dateLst
[[1]]
[1] "2015-08-11"

> dateVector <- unlist(dateLst)
> dateVector
[1] 16658


同样的原因,在使用sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)时,如果X为日期型向量,FUN返回日期,那么结果不会是预期的日期型向量,如下:
> date.vector.string <- c("20010101")
> date.vector <- sapply(date.vector.string, get.date)
> date.vector
20010101 
   11323 

其中:
# Get date from date string. Assumed the format of date string is like "20011230"
#
# Args:
# date.string: date string like "20011230"
#
# Returns:
# date.
get.date <- function(date.string){
  #  deal with the Error in strptime(x, format, tz = "GMT") : input string is too long
  if(nchar(date.string) != 8)
    return(NA)
 
  date <- try(as.Date(date.string, "%Y%m%d"))
  return(date)
}

sapply的结果,看起来可以认为是先调用lapply,得到的list后,调用unlist,试图得到与date.vector.string同类型的结果即向量。

考虑到日期型列表转换为向量的麻烦,最好的方法就是不要出现日期型列表,尽量用向量。

关于对
> dateVector <- unlist(dateLst)
> dateVector
[1] 16658

的解释,可以参加下列代码:
> as.Date(16658, origin = "1970-01-01")
[1] "2015-08-11"

看来unlist时默认了一个时间点1970-01-01.
原文地址:https://www.cnblogs.com/lizichao/p/4721276.html