Sapply更改我的POSIXlt日期变量的格式

时间:2014-11-28 13:42:47

标签: r sapply posixlt

我正在使用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"

我尝试了formatas.POSIXlt等方法。没有任何效果。

2 个答案:

答案 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对象内部为listlapply,朋友将其视为列表。这意味着您的函数会将mday添加到此列表的每个元素,从而将它们转换为列表。

@ akrun的回答显示了你应该怎么做。

答案 1 :(得分:3)

尝试

d <- as.POSIXlt('2012-02-01', tz='UTC')
d$mday <- 14
d
#[1] "2012-02-14 UTC"