简体   繁体   English

如何在不更改功能的情况下使用R Apply

[英]How to use R apply without changing a function

I have a basic character date to POSIXct function 我有POSIXct函数的基本字符日期

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" . 我想将日期的数据类型更改为POSIXct ,因此想将此函数charDateToPosixct应用于格式为"%m/%d/%y"每一行。

Use an anonymous function in apply like this 在这样的apply使用匿名函数

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 您可以将使用的数值向量转换为apply 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. 或者,您可以使用lapply获取POSIXct对象的列表。 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 cReduce结合使用(您必须使用as.character因为在创建data.frame时隐式使用了stringsAsFactors=TRUE

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 或者,如果您有2个向量,则甚至不需要data.frame

do.call(c, lapply(seq_along(chrDate), function(i) {
    charDateToPosixct(chrDate[i], "%m/%d/%Y", timeZone[i])
}))

Or, using Reduce 或者,使用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 我的时区是CDT,所以以上任何一个都给我

[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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM