I am using POSIXlt
to keep the dates. What I want to do is to change month days of each date variable as follows, but it gives an error. (Below, d
is a list of dates.)
> 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
I realized that it changes the format of my variable.
> 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"
What can I do to get following
> d
[1] "2012-02-14 UTC"
I tried format
, as.POSIXlt
and etc. methods. Nothing worked.
Let's look at what happens. To make it easier, I'll fix you anonymous function to return
x
:A
POSIXlt
object is alist
internally andlapply
and friends treat it as a list. This means your function addsmday
to each element of this list, thereby turning them into lists.@akrun's answer shows how you should do this.