Reputation: 649
I have a basic character date to POSIXct
function
charDateToPosixct <- function(chrDate, format, timeZone) {
as.POSIXct(chrDate, format=format, tz=timeZone)
}
I have a data frame with date as character and timezone.
chrDate <- c("4/25/2012","4/24/2012","4/16/2012","6/30/2012")
timeZone <- c("US/Eastern","US/Central","US/Pacific","US/Eastern")
df <- data.frame(date=chrDate,timezone=timeZone)
str(df)
'data.frame': 4 obs. of 2 variables:
$ date : Factor w/ 4 levels "4/16/2012","4/24/2012",..: 3 2 1 4
$ timezone: Factor w/ 3 levels "US/Central","US/Eastern",..: 2 1 3 2
I want to change the data type of date to POSIXct
and so want to apply this function charDateToPosixct
to each row with the format "%m/%d/%y"
.
Upvotes: 0
Views: 218
Reputation: 49810
Use an anonymous function in apply
like this
apply(df, 1, function(x) charDateToPosixct(x[1], "%m/%d/%y", x[2]))
#[1] 1587787200 1587704400 1587020400 1593489600
edit
You could convert the numeric vector you got using apply
to POSIXct
as.POSIXct(apply(df, 1, function(x) charDateToPosixct(x[1], "%m/%d/%y", x[2])), origin='1970-01-01')
[1] "2020-04-25 05:00:00 CDT" "2020-04-24 06:00:00 CDT" "2020-04-16 08:00:00 CDT" "2020-06-30 05:00:00 CDT"
Or, you can use lapply
to get a list of POSIXct
objects. Then you can combine with do.call
c
, or Reduce
(You have to use as.character
because you implicitly used stringsAsFactors=TRUE
when you created the data.frame
)
do.call(c, lapply(seq_len(NROW(df)), function(i) {
charDateToPosixct(as.character(df$date[i]), "%m/%d/%Y", as.character(df$timezone[i]))
}))
Or, if you have 2 vectors, you don't even need the data.frame
do.call(c, lapply(seq_along(chrDate), function(i) {
charDateToPosixct(chrDate[i], "%m/%d/%Y", timeZone[i])
}))
Or, using Reduce
Reduce(c, lapply(seq_along(chrDate), function(i) {
charDateToPosixct(chrDate[i], "%m/%d/%Y", timeZone[i])
}))
My timezone is CDT, so any of the above give me
[1] "2012-04-24 23:00:00 CDT" "2012-04-24 00:00:00 CDT" "2012-04-16 02:00:00 CDT" "2012-06-29 23:00:00 CDT"
Upvotes: 3