将 POSIXct 对象传递给函数 returns 数值向量

Passing POSIXct object to function returns numeric vector

我正在尝试对 POSIXct 向量进行一些操作,但是当我将其传递给函数时,该向量变为 numeric 向量,而不是保留 POSIXct class,即使函数本身只有returns对象:

# Sample dates from vector and it's class.
> dates <- as.POSIXct(c("2012-02-01 12:32:00", "2012-10-24 17:25:56", "2008-09-26 17:13:31", "2011-08-23 11:11:17,", "2015-09-19 22:28:33"), tz = "America/Los_Angeles")
> dates
[1] "2012-02-01 12:32:00 PST" "2012-10-24 17:25:56 PDT" "2008-09-26 17:13:31 PDT" "2011-08-23 11:11:17 PDT" "2015-09-19 22:28:33 PDT"
> class(dates)
[1] "POSIXct" "POSIXt" 
# Simple subset is retaining original class.
> qq <- dates[1:5]
> qq
[1] "2012-02-01 12:32:00 PST" "2012-10-24 17:25:56 PDT" "2008-09-26 17:13:31 PDT" "2011-08-23 11:11:17 PDT" "2015-09-19 22:28:33 PDT"
> class(qq)
[1] "POSIXct" "POSIXt" 
# sapply on the same subset using simple "return" function changes class to "numeric" - why? How to retain "POSIXct"?
> qq2 <- sapply(dates[1:5], function(x) x)
> qq2
[1] 1328128320 1351124756 1222474411 1314123077 1442726913
> class(qq2)
[1] "numeric"

为什么会这样?如何保留原始向量的 POSIXct class?我知道 POSIXct numeric,但我想保留原来的 class 以提高可读性。

我们可以使用 lapply 而不是 sapply,因为 sapply 默认具有选项 simplify = TRUE。因此,如果 list 元素的长度相同,它将根据 list 元素和 POSIXct 的长度将其简化为 vectormatrix存储为 numeric.

lst <- lapply(dates, function(x) x)

如果我们需要使用sapply,那么一个选项就是simplify = FALSE

lst <- sapply(dates, function(x) x, simplify=FALSE)

应用函数后,如果我们需要作为向量输出,

do.call("c", lst)

关于时区的变化,在?DateTimeClasses

中有记载

Using c on "POSIXlt" objects converts them to the current time zone, and on "POSIXct" objects drops any "tzone" attributes (even if they are all marked with the same time zone).

因此,可能的选择是(如@kmo 评论中所述)

.POSIXct(lst, tz = "America/Los_Angeles")
#[1] "2012-02-01 12:32:00 PST" "2012-10-24 17:25:56 PDT" "2008-09-26 17:13:31 PDT" "2011-08-23 11:11:17 PDT" "2015-09-19 22:28:33 PDT"

或者如评论中提到的@thelatemail

.POSIXct(sapply(dates,I), attr(dates,"tzone") )