Я пытаюсь вычислить разницу во времени между двумя столбцами для строк, в которых выполняется определенный критерий.
dates1 <- c("1899-12-31 12:20:00 PMT", "1899-12-31 15:30:00 PMT", "1899-12-31 13:20:00 PMT", "1899-12-31 11:50:00 PMT",
NA)
dates2 <- c("1899-12-31 11:13:00 PMT", "1899-12-31 11:41:00 PMT", "1899-12-31 14:04:00 PMT", "1899-12-31 13:03:00 PMT",
"1899-12-31 13:18:00 PMT")
site <- c(15, 16, 18, 18,
15)
DS <- as.data.frame(cbind(site, dates1 , dates2))
## convert to POSIXct format
DS[, 2:3] <- lapply(DS[, 2:3], function(x) as.POSIXct(strptime(x,"%Y-%m-%d %H:%M:%S ",tz="")))
## create a new columns with the time difference between dates1 and dates2 in %H:%M:%S format if site=18 , else take value from column dates1
DS$output <- ifelse(DS$site ==18,
difftime(DS$dates1, DS$dates2, units = "mins"),
DS$dates1)
## using the code above doesnt work because:
#1- using the difftime function I can't choose the "%H:%M:%S" for the output
#2- for sites != 18, the dates1 lose its "%H:%M:%S format
# I have also tried to use:
DS$output <- ifelse(DS$site ==18,
difftime(DS$dates1, DS$dates2, units = "mins"),
0)
## and then convert the difference in minutes to %H:%M:%S format using
DS$output<- as.difftime(DS$output , format = "%H:%M:%S", units = "mins")
## but it doesnt work.
## the output should be something like:
output<- c("12:20:00", "15:30:00","00:44:00", "01:13:00", NA)
DS.out <- cbind(DS, output)
> DS.out
site dates1 dates2 output
1 15 1899-12-31 12:20:00 PMT 1899-12-31 11:13:00 PMT 12:20:00
2 16 1899-12-31 15:30:00 PMT 1899-12-31 11:41:00 PMT 15:30:00
3 18 1899-12-31 13:20:00 PMT 1899-12-31 14:04:00 PMT 00:44:00
4 18 1899-12-31 11:50:00 PMT 1899-12-31 13:03:00 PMT 01:13:00
5 15 <NA> 1899-12-31 13:18:00 PMT <NA>
#Where output is the time difference calculated for rows 3 and 4 (site=18)
#or a copy of the time from dates 1 for the other rows (with sites different from 18).
Есть ли способ расчета разницы во времени в формате H%:% M:% S с использованием другой функции?