简体   繁体   中英

How to calculate mean of two timestamp columns in R?

I have data frame in R, where two columns are datetimes (POSIX class). I need to calculate mean datetime by each row.

Here's some reproducible example:

a <- c(
 "2018-10-11 15:22:17",
 "2018-10-10 16:30:37",
 "2018-10-10 16:52:46", 
 "2018-10-10 16:58:33", 
 "2018-10-10 16:32:24")

b <- c(
  "2018-10-11 15:25:12", 
  "2018-10-10 16:30:39", 
  "2018-10-10 16:55:14", 
  "2018-10-10 16:58:53", 
  "2018-10-10 16:32:27")

a <- strptime(a, format = "%Y-%m-%d %H:%M:%S")
b <- strptime(b, format = "%Y-%m-%d %H:%M:%S")

f <- data.frame(a, b)

The results should be like that:

                    a                   b           time_mean
1 2018-10-11 15:22:17 2018-10-11 15:25:12 2018-10-11 15:23:44
2 2018-10-10 16:30:37 2018-10-10 16:30:39 2018-10-10 16:30:38
3 2018-10-10 16:52:46 2018-10-10 16:55:14 2018-10-10 16:54:00
4 2018-10-10 16:58:33 2018-10-10 16:58:53 2018-10-10 16:58:43
5 2018-10-10 16:32:24 2018-10-10 16:32:27 2018-10-10 16:32:25

I tried following:

apply(f, 1, function(x) mean)
apply(f, 1, function(x) mean(c(x[1], x[2])))

Instead of using apply (which can convert it to a matrix and then strip off the class attributes), use Map

f$time_mean <- do.call(c, Map(function(x, y) mean(c(x, y)), a, b))
f$time_mean
#[1] "2018-10-11 15:23:44 EDT" "2018-10-10 16:30:38 EDT" "2018-10-10 16:54:00 EDT" "2018-10-10 16:58:43 EDT"
#[5] "2018-10-10 16:32:25 EDT"

Or as it is from data.frame f

do.call(c, Map(function(x, y) mean(c(x, y)), f$a, f$b))

Also, another option is converting to numeric class with ?xtfrm (that also has POSIXlt method dispatch), do the rowMeans and convert to DateTime class as in @jay.sf's post

as.POSIXlt(rowMeans(sapply(f, xtfrm)), origin = "1970-01-01")
#[1] "2018-10-11 15:23:44 EDT" "2018-10-10 16:30:38 EDT" "2018-10-10 16:54:00 EDT" "2018-10-10 16:58:43 EDT"
#[5] "2018-10-10 16:32:25 EDT"

You could calculate with the numerics.

f$time_mean <- as.POSIXct(sapply(seq(nrow(f)), function(x) 
  mean(as.numeric(f[x, ]))), origin="1970-01-01")
f
#                     a                   b           time_mean
# 1 2018-10-11 15:22:17 2018-10-11 15:25:12 2018-10-11 15:23:44
# 2 2018-10-10 16:30:37 2018-10-10 16:30:39 2018-10-10 16:30:38
# 3 2018-10-10 16:52:46 2018-10-10 16:55:14 2018-10-10 16:54:00
# 4 2018-10-10 16:58:33 2018-10-10 16:58:53 2018-10-10 16:58:43
# 5 2018-10-10 16:32:24 2018-10-10 16:32:27 2018-10-10 16:32:25

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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