Sapply Change the Format of my POSIXlt Date Variable

157 views Asked by At

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.

2

There are 2 answers

0
Roland On

Let's look at what happens. To make it easier, I'll fix you anonymous function to return 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

A POSIXlt object is a list internally and lapply and friends treat it as a list. This means your function adds mday to each element of this list, thereby turning them into lists.

@akrun's answer shows how you should do this.

0
akrun On

Try

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