问题
I have a data frame of character times that I need to average by provider, but I'm not sure how to average them using just the time without the date. For the example below:
provider time
USA 9:26:46
USDA 9:26:18
USDA 9:10:17
OIL 10:00:00
USA 6:20:56
USDA 7:19:13
OIL 11:00:00
The correct output for OIL would be the average between 10:00 and 11:00, and would look like:
provider average
OIL 10:30
Does anyone know how to average just time without incorporating date using POSIX?
回答1:
mean
works as expected. You can format the date to %H:%M:%S afterwards.
df <- read.table(text="provider time
USA 9:26:46
USDA 9:26:18
USDA 9:10:17
OIL 10:00:00
USA 6:20:56
USDA 7:19:13
OIL 11:00:00",head=TRUE)
df$time <- as.POSIXct(df$time,format="%T",origin="1970-01-01")
format(as.POSIXct(tapply(df$time,df$provider,mean),origin="1970-01-01"),format="%H:%M:%S")
OIL USA USDA
"10:30:00" "07:53:51" "08:38:36"
To get the providers' name :
m <- format(as.POSIXct(tapply(df$time,df$provider,mean),origin="1970-01-01"),format="%H:%M:%S")
m <- as.data.frame(m)
m$provider <- row.names(m)
来源:https://stackoverflow.com/questions/31710890/r-posix-hms-time-average