[英]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
c
或Reduce
结合使用(您必须使用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.