标签时间最小值和最大值出现在 R 数据帧中

Label time of day min and max values occur in R dataframe

我有一个时间序列数据 (Q),我想创建一个列(类别),分别用标签 Min 和 Max 标记每天出现的最小 Q 和最大 Q。下面的代码标识了一天中出现最小值 (Time_of_min_Q) 和最大值 (Time_of_max_Q) 的时间。我使用相同的技术添加相应的标签,但它不起作用。感谢您的建议。

library(dplyr)
set.seed(12345)
dateTime <- seq(as.POSIXct("2005-01-01 00:00:00", tz = "GMT"),
                as.POSIXct("2005-01-03 00:00:00", tz = "GMT"),
                by = 60*15)
Q <- sample(100:395,193,rep=TRUE)
df <- data.frame(dateTime,Q)
df$Time<-format(as.POSIXct(dateTime), format = "%H:%M:%S")

df1<-df %>% 
  group_by(Date = as.Date(dateTime)) %>% 
  mutate(Time_of_max_Q = Time[which.max(Q)],
         Time_of_min_Q = Time[which.min(Q)],
         Category = ifelse(Time[which.max(Q)],"Max",
                           ifelse(Time[which.min(Q)],"Min",NA)))

ifelse中的条件不合逻辑。它可以用 == 创建为合乎逻辑的。根据?ifelse

test - an object which can be coerced to logical mode.

library(dplyr)
df %>% 
  group_by(Date = as.Date(dateTime)) %>% 
  mutate(Time_of_max_Q = Time[which.max(Q)],
         Time_of_min_Q = Time[which.min(Q)],
         Category = ifelse(Q== max(Q),"Max",
                           ifelse(Q == min(Q),"Min",NA))) %>%  
  ungroup

如果 max/min 值有联系,则子集 Timewhich.max/which.min returns 分别是第一个 max/min 值的索引)并使用== 与原始 'Time' 列

df %>% 
  group_by(Date = as.Date(dateTime)) %>% 
  mutate(Time_of_max_Q = Time[which.max(Q)],
         Time_of_min_Q = Time[which.min(Q)],
         Category = ifelse(Time[which.max(Q)] == Time,"Max",
                           ifelse(Time[which.min(Q)] == Time,"Min",NA)))