У меня есть набор данных, состоящий из показаний монитора для системы отслеживания местоположения. К сожалению, я недостаточно опытен, чтобы воспроизвести его случайным образом, поэтому вот первые несколько записей:
Time TagID MonitorID Location
2017-10-31 23:03:26 1427435 1352303 A4.18
2017-10-31 23:06:02 1427435 1352303 A4.18
2017-10-31 23:06:20 1427435 1352303 A4.18
2017-10-31 23:06:50 1427435 1352303 A4.18
2017-10-31 23:06:51 1427435 1352303 A4.18
2017-10-31 23:07:20 1427435 1352303 A4.18
.
.
.
2017-11-22 22:29:55 1427435 1349044 B6.24
2017-11-22 22:30:22 1427435 286748 B6.41
2017-11-22 22:30:25 1427435 1349044 B6.24
2017-11-22 22:30:40 1427435 286748 B6.41
2017-11-22 22:30:41 1427435 286748 B6.41
2017-11-22 22:30:55 1427435 1349044 B6.24
Я пытаюсь определить время, которое метка RFID провела в определенном месте монитора, глядя на то, сколько времени прошло до изменения показаний MonitorID. Я делаю это с помощью этой функции, которую я написал:
elapsed_time <- function(x) {
# Prepare variables
current_monitor <- x$MonitorID[1]
start_time <- x$Time[1]
end_time <- NULL
output <- data.frame("Date" = as.POSIXct(as.character()), "MonitorID" = as.integer(),
"Minutes_elapsed" = as.integer())
# For loop to iterate over rows
for (i in 1:nrow(x)) {
# if the new monitor is the same as the old one then go to next iteration
# otherwise calculate the time between dates, add values to output
if (x$MonitorID[i] == current_monitor & i != nrow(x)) {
next
} else {
# Mark what the time is when the location changes
end_time <- x$Time[i]
# Calculate time difference
time_spent <- difftime(end_time, start_time, units = "mins")
# Create temporary data frame to append to output
temp <- data.frame(start_time, current_monitor, time_spent)
# Append temp to output
output <- rbind(output, setNames(temp, names(output)))
# Set the new start time to the current time
start_time <- end_time
# Set the current monitor tracker to the new monitor
current_monitor <- x$MonitorID[i]
}
}
# Add monitor mappings to output
output <- left_join(output, Mmappings[,c(1,2)], by="MonitorID")
return(output)
}
Последнюю строку можно игнорировать, она просто предназначена для переназначения фактического имени местоположения на показания MonitorID. Эта функция работает так, как хотелось бы, однако для работы только с одним монитором требуется очень много времени (~ 4 минуты), и я хотел бы использовать ее одновременно с примерно 95 мониторами в другой функции. Я уверен, что есть более эффективный способ написать эту функцию, чтобы сократить время.
РЕДАКТИРОВАТЬ: Вот пример вывода по запросу:
Date MonitorID Minutes_elapsed Location
1 2017-10-31 23:03:26 1352303 3.36666667 mins A4.18
2 2017-10-31 23:06:48 0 0.03333333 mins A4.20
3 2017-10-31 23:06:50 1352303 0.45000000 mins A4.18
4 2017-10-31 23:07:17 0 0.05000000 mins A4.20
5 2017-10-31 23:07:20 1352303 0.45000000 mins A4.18
6 2017-10-31 23:07:47 0 0.05000000 mins A4.20
В этом случае время между изменениями невелико, поскольку иногда показания перескакивают на другие мониторы, но это не имеет значения.
lead/lag
? - person zx8754   schedule 23.01.2018