1

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等等方法。没有任何效果。

4

2 回答 2

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 的回答显示了你应该如何做到这一点。

于 2014-11-28T13:59:29.843 回答
3

尝试

d <- as.POSIXlt('2012-02-01', tz='UTC')
d$mday <- 14
d
#[1] "2012-02-14 UTC"
于 2014-11-28T13:46:12.280 回答