将POSIXct对象传递给函数会返回数字向量

时间:2016-07-07 09:18:52

标签: r vector numeric posixct coercion

我试图对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,但我希望保留原始类以便于阅读。

1 个答案:

答案 0 :(得分:2)

我们可以使用lapply代替sapply,因为sapply默认情况下会选择simplify = TRUE。因此,如果list元素的长度相同,则会将其简化为vectormatrix,具体取决于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") )