我正在使用POSIXlt
来保留日期。我想要做的是更改每个日期变量的月份日,如下所示,但它给出了一个错误。 (下面,d
是日期列表。)
> d
[1] "2012-02-01 UTC"
> a = sapply(d, function(x) { x$mday=14;})
Warning messages:
1: In x$mday = 14 : Coercing LHS to a list
2: In x$mday = 14 : Coercing LHS to a list
3: In x$mday = 14 : Coercing LHS to a list
4: In x$mday = 14 : Coercing LHS to a list
5: In x$mday = 14 : Coercing LHS to a list
6: In x$mday = 14 : Coercing LHS to a list
7: In x$mday = 14 : Coercing LHS to a list
8: In x$mday = 14 : Coercing LHS to a list
9: In x$mday = 14 : Coercing LHS to a list
> a
sec min hour mday mon year wday yday isdst
14 14 14 14 14 14 14 14 14
我意识到它会改变我变量的格式。
> class(d)
[1] "POSIXlt" "POSIXt"
> a = sapply(d, function(x) { format(x, format = "%Y-%m-%d")})
> a
sec min hour mday mon year wday yday isdst
"0" "0" "0" "14" "1" "112" "0" "91" "0"
我该怎么做才能获得以下
> d
[1] "2012-02-14 UTC"
我尝试了format
,as.POSIXlt
等方法。没有任何效果。
答案 0 :(得分:4)
让我们来看看会发生什么。为了方便起见,我将修复匿名函数以返回x
:
d <- as.POSIXlt(c('2012-02-01', '2012-02-02'), tz='UTC')
sapply(d, function(x) { x$mday=14; x})
# sec min hour mday mon year wday yday isdst
# 0 0 0 1 1 112 3 31 0
# 0 0 0 2 1 112 4 32 0
#mday 14 14 14 14 14 14 14 14 14
#Warning messages:
#1: In x$mday = 14 : Coercing LHS to a list
#2: In x$mday = 14 : Coercing LHS to a list
#3: In x$mday = 14 : Coercing LHS to a list
#4: In x$mday = 14 : Coercing LHS to a list
#5: In x$mday = 14 : Coercing LHS to a list
#6: In x$mday = 14 : Coercing LHS to a list
#7: In x$mday = 14 : Coercing LHS to a list
#8: In x$mday = 14 : Coercing LHS to a list
#9: In x$mday = 14 : Coercing LHS to a list
POSIXlt
对象内部为list
,lapply
,朋友将其视为列表。这意味着您的函数会将mday
添加到此列表的每个元素,从而将它们转换为列表。
@ akrun的回答显示了你应该怎么做。
答案 1 :(得分:3)
尝试
d <- as.POSIXlt('2012-02-01', tz='UTC')
d$mday <- 14
d
#[1] "2012-02-14 UTC"