我试图对POSIXct
向量进行一些操作,但当我将其传递给函数时,向量会变为numeric
向量,而不是保留POSIXct
} class,即使函数本身只返回对象:
# 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
类?我知道POSIXct
是 numeric
,但我希望保留原始类以便于阅读。
答案 0 :(得分:2)
我们可以使用lapply
代替sapply
,因为sapply
默认情况下会选择simplify = TRUE
。因此,如果list
元素的长度相同,则会将其简化为vector
或matrix
,具体取决于list
元素的长度和POSIXct
存储为numeric
。
lst <- lapply(dates, function(x) x)
如果我们需要使用sapply
,则选项simplify = FALSE
lst <- sapply(dates, function(x) x, simplify=FALSE)
应用函数后,如果我们需要作为矢量输出,
do.call("c", lst)
关于时区的变化,它记录在?DateTimeClasses
使用c on&#34; POSIXlt&#34;对象将它们转换为当前时区, 并且在&#34; POSIXct&#34;物品掉落任何&#34; tzone&#34;属性(即使它们 都标有相同的时区)。
因此,可能的选择是(如@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") )