确实,不同的as.Date 方法存在差异,这就是原因(或者更确切地说是“如何”):
首先,你的例子:
> as.Date(c(ind = "2015-07-04", nyd = "2016-01-01"))
[1] "2015-07-04" "2016-01-01"
这里我们使用方法as.Date.character:
> as.Date.character
function (x, format = "", ...)
{
charToDate <- function(x) {
xx <- x[1L]
if (is.na(xx)) {
j <- 1L
while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
if (is.na(xx))
f <- "%Y-%m-%d"
}
if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d",
tz = "GMT")) || !is.na(strptime(xx, f <- "%Y/%m/%d",
tz = "GMT")))
return(strptime(x, f))
stop("character string is not in a standard unambiguous format")
}
res <- if (missing(format))
charToDate(x)
else strptime(x, format, tz = "GMT")
as.Date(res)
}
<bytecode: 0x19d3dff8>
<environment: namespace:base>
无论是否给出格式,您的向量都会传递给strptime,后者将其转换为类POSIXlt,然后再次传递给as.Date,但这次使用方法as.Date.POSIXlt,即:
> as.Date.POSIXlt
function (x, ...)
.Internal(POSIXlt2Date(x))
<bytecode: 0x19d2df50>
<environment: namespace:base>
意味着最终用于转换为 Date 类的函数是 POSIXlt2Date 调用的 C 函数(快速查看文件 names.c 表明该函数是文件 datetime.c 中的 do_POSIXlt2D)。供参考,这里是:
SEXP attribute_hidden do_POSIXlt2D(SEXP call, SEXP op, SEXP args, SEXP env)
{
SEXP x, ans, klass;
R_xlen_t n = 0, nlen[9];
stm tm;
checkArity(op, args);
PROTECT(x = duplicate(CAR(args)));
if(!isVectorList(x) || LENGTH(x) < 9)
error(_("invalid '%s' argument"), "x");
for(int i = 3; i < 6; i++)
if((nlen[i] = XLENGTH(VECTOR_ELT(x, i))) > n) n = nlen[i];
if((nlen[8] = XLENGTH(VECTOR_ELT(x, 8))) > n) n = nlen[8];
if(n > 0) {
for(int i = 3; i < 6; i++)
if(nlen[i] == 0)
error(_("zero-length component in non-empty \"POSIXlt\" structure"));
if(nlen[8] == 0)
error(_("zero-length component in non-empty \"POSIXlt\" structure"));
}
/* coerce relevant fields to integer */
for(int i = 3; i < 6; i++)
SET_VECTOR_ELT(x, i, coerceVector(VECTOR_ELT(x, i), INTSXP));
PROTECT(ans = allocVector(REALSXP, n));
for(R_xlen_t i = 0; i < n; i++) {
tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
tm.tm_mday = INTEGER(VECTOR_ELT(x, 3))[i%nlen[3]];
tm.tm_mon = INTEGER(VECTOR_ELT(x, 4))[i%nlen[4]];
tm.tm_year = INTEGER(VECTOR_ELT(x, 5))[i%nlen[5]];
/* mktime ignores tm.tm_wday and tm.tm_yday */
tm.tm_isdst = 0;
if(tm.tm_mday == NA_INTEGER || tm.tm_mon == NA_INTEGER ||
tm.tm_year == NA_INTEGER || validate_tm(&tm) < 0)
REAL(ans)[i] = NA_REAL;
else {
/* -1 must be error as seconds were zeroed */
double tmp = mktime00(&tm);
REAL(ans)[i] = (tmp == -1) ? NA_REAL : tmp/86400;
}
}
PROTECT(klass = mkString("Date"));
classgets(ans, klass);
UNPROTECT(3);
return ans;
}
不幸的是,我对 C 的理解太有限,无法知道为什么这里会丢失属性。我的猜测是它发生在 coerceVector 操作期间或 POSIXlt 列表的每个元素被单独强制转换为整数时(如果这是第 1268-70 行发生的情况)。
但是让我们看看另一个as.Date 方法,从主要的罪犯as.Date.POSIXct 开始:
> as.Date.POSIXct
function (x, tz = "UTC", ...)
{
if (tz == "UTC") {
z <- floor(unclass(x)/86400)
attr(z, "tzone") <- NULL
structure(z, class = "Date")
}
else as.Date(as.POSIXlt(x, tz = tz))
}
<bytecode: 0x19c268bc>
<environment: namespace:base>
有了这个,如果没有给出时区,或者时区是“UTC”,该函数只是操纵POSIXct列表来提取可以解析为日期对象的数据,因此不会丢失属性,但是如果给定了任何其他时区,则它会被转换为POSIXlt 对象,因此会进一步传递给相同的POSIXlt2Date 内部,最终会失去其属性!确实:
> as.Date(c(a = as.POSIXct("2016-01-01")), tz="UTC")
a
"2015-12-31"
> as.Date(c(a = as.POSIXct("2016-01-01")), tz="CET")
[1] "2016-01-01"
最后,正如@Roland 提到的,as.Date.numeric 确实保留了这些属性:
> as.Date.numeric
function (x, origin, ...)
{
if (missing(origin))
stop("'origin' must be supplied")
as.Date(origin, ...) + x
}
<bytecode: 0x568943d4>
<environment: namespace:base>
origin通过as.Date.character转换为Date,然后加上numeric的向量,因此保留了属性:
> c(a=1) + 2
a
3
自然而然:
> c(a=16814) + as.Date("1970-01-01")
a
"2016-01-14"
在解决此差异之前,我认为,您必须保留属性的唯一解决方案是首先转换为 POSIXct(但要注意时区问题)或数字,或者复制原始属性向量:
> before <- c(ind = "2015-07-04", nyd = "2016-01-01")
> after <- as.Date(before)
> names(after) <- names(before)
> after
ind nyd
"2015-07-04" "2016-01-01"