Reputation: 3756
I have a data frame df
with a column time
that contains timestamps and a function from.timestamp
from.timestamp = function(timestamp) {
return(as.POSIXlt(timestamp/1e3, origin="1970-01-01 00:00:00 GMT"))
}
that converts a timestamp to a date type. How do I modify the data frame so that all timestamps are converted to dates?
My approach
I'm trying the following:
df$time <- apply(as.array(df$time), MARGIN=1, FUN=from.timestamp)
The resulting column entries for time
do not look like a date, but are rather a sequence of numbers, e.g., 1.034, 59.000, 23.000, 7.000, 5.000, 113.000, 5.000, 157.000, 1.000
.
dput(df)
gives:
structure(list(time = c(1370674741034, 1372671995085, 1370847555008, 1371456058556, 1372570911379, 1371937835807)), .Names = "time", row.names = 8831395:8831400, class = "data.frame")
Upvotes: 1
Views: 929
Reputation: 57686
Just do
df$time <- from.timestamp(df$time)
The reason you're getting the strange behaviour is because POSIXlt
objects are actually lists, with components for year, month, day, etc. In your code, apply
receives from from.timestamp
a sequence of lists, which it combines into a single list. In doing so, it strips the class information from the result, which is why you saw your odd numbers. These odd numbers are actually the individual components of the POSIXlt object representing that datetime: seconds, minutes, hour, day of month, month, year, weekday, day in year.
Upvotes: 2