user1946217
user1946217

Reputation: 1753

Apply function doesn't result in Date format

I am facing a problem when I apply an apply function on a Date column. The Date is not being displayed correctly. Need help on this

> head(dataF)
[1] "4-Sep-06"  "27-Oct-06" "8-Jan-07"  "28-Jan-07" "5-Jan-07"  "28-Jan-07"
> res <- apply(dataF, 2, dmy)
> head(res)
          DateM
[1,]    1157328000
[2,]    1161907200
[3,]    1168214400
[4,]    1169942400
[5,]    1167955200
[6,]    1169942400

Upvotes: 1

Views: 99

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99351

If you want the format to look like a date object, change it to a date object. That way, it actually is a date object.

> dataF <- c("4-Sep-06", "27-Oct-06", "8-Jan-07", 
             "28-Jan-07", "5-Jan-07",  "28-Jan-07")
> as.Date(dataF, "%d-%b-%y")
[1] "2006-09-04" "2006-10-27" "2007-01-08" "2007-01-28" "2007-01-05" "2007-01-28"

Upvotes: 0

merlin2011
merlin2011

Reputation: 75585

Regardless of what you want to do with the output, you should not need to use apply or its cousins when the function dmy already handles vectors. Just use

res <- dmy(dataF)

Having said that, if you just want to learn how to use apply, Ananda's comment is correct. The following should also give you correct results.

res <- lapply(dataF, dmy)

Here is a more elaborate example where we only replace dates in a couple of columns:

dataF <- data.frame(x = c("4-Sep-06", "27-Oct-06", "8-Jan-07", 
                          "28-Jan-07", "5-Jan-07", "28-Jan-07"),
                    y = c("4-Jan-06", "27-Jan-06", "8-Feb-07", 
                          "28-Feb-07", "5-Mar-07", "28-Mar-07"),
                    z = c(1:6))
dataF
#           x         y z
# 1  4-Sep-06  4-Jan-06 1
# 2 27-Oct-06 27-Jan-06 2
# 3  8-Jan-07  8-Feb-07 3
# 4 28-Jan-07 28-Feb-07 4
# 5  5-Jan-07  5-Mar-07 5
# 6 28-Jan-07 28-Mar-07 6

library(lubridate)
## The third column is not a date
## Just replace the first two columns directly
dataF[1:2] <- lapply(dataF[1:2], dmy)
dataF
#            x          y z
# 1 2006-09-04 2006-01-04 1
# 2 2006-10-27 2006-01-27 2
# 3 2007-01-08 2007-02-08 3
# 4 2007-01-28 2007-02-28 4
# 5 2007-01-05 2007-03-05 5
# 6 2007-01-28 2007-03-28 6

Upvotes: 2

Related Questions