首页 > 解决方案 > 求一天的最小值和最大值对应的时间

问题描述

下面是我的数据的样子。我需要找到每天的最高和最低温度以及相应的温度。

   Temp          date             time
280.9876771 01-01-79    03:00:00
291.9695498 01-01-79    06:00:00
294.9583426 01-01-79    09:00:00
290.2357847 01-01-79    12:00:00
286.2944531 01-01-79    15:00:00
282.9282138 01-01-79    18:00:00
280.326689  01-01-79    21:00:00
279.2551605 02-01-79    00:00:00
281.3981824 02-01-79    03:00:00
293.076125  02-01-79    06:00:00
295.8072204 02-01-79    09:00:00

这段代码我每天尝试最低和最高温度。

library(xts)
read.csv("hourly1.csv", header = T) -> hourly1
xts(hourly1$Temp, as.Date(hourly1$date)) -> temp_date1
apply.daily(temp_date1, min) -> mintemp1_date
apply.daily(temp_date1, max) -> maxtemp1_date

我需要有关如何查找最低和最高温度的时间的帮助

标签: r

解决方案


library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

dataset <- read.table(text = 'Temp          date             time
280.9876771 01-01-79    03:00:00
291.9695498 01-01-79    06:00:00
294.9583426 01-01-79    09:00:00
290.2357847 01-01-79    12:00:00
286.2944531 01-01-79    15:00:00
282.9282138 01-01-79    18:00:00
280.326689  01-01-79    21:00:00
279.2551605 02-01-79    00:00:00
281.3981824 02-01-79    03:00:00
293.076125  02-01-79    06:00:00
295.8072204 02-01-79    09:00:00',
                      header = TRUE,
                      stringsAsFactors = FALSE)

dataset %>%
  group_by(date) %>%
  summarise(min_temp = min(Temp),
            min_temp_time = time[which.min(x = Temp)],
            max_temp = max(Temp),
            max_temp_time = time[which.max(x = Temp)])
#> # A tibble: 2 x 5
#>   date     min_temp min_temp_time max_temp max_temp_time
#>   <chr>       <dbl> <chr>            <dbl> <chr>        
#> 1 01-01-79     280. 21:00:00          295. 09:00:00     
#> 2 02-01-79     279. 00:00:00          296. 09:00:00

reprex 包(v0.3.0)于 2019 年 6 月 15 日创建

希望这可以帮助。


推荐阅读