用R中的日期和最短时间排序

时间:2016-12-27 06:21:48

标签: r date time

这项任务对我来说很难。我需要找到每月30/31天的每一小时(最短记录时间)的临时值。但是,传感器在不规则周期测量温度值(输入文件作为图像附加)。我想为此编写R代码。例如输出:

1/6/2016 0.00 90.45
1/6/2016 1.01 92.54
1/6/2016 2.12 94.95

1/6/2016 21.53 95.85

类似的样本数据框:

  

样本< -     data.frame(       date = c(rep(“2016-06-01”,13),NA,NA,rep(“2016-06-01”,3),NA,NA,rep(“2016-06-01”,3) ,NA,rep(“2016-06-02”,2)),       time = c(“0:00”,“0:10”,“0:20”,“0:30”,“1:01”,“1:11”,“1:21”,“1:31 “,”1:41“,”1:51“,”2:12“,”2:42“,”2:52“,NA,NA,”12:03“,”12:13“,”12 :23“,NA,NA,”21:53“,”21:54“,”23:14“,NA,NA,NA),       temp = c(90.45,91.29,90.88,91.22,92.54,92.57,93.18,93.9,94.51,94.37,95.96,95.32,95.2,NA,NA,95.37,95.52,95.35,NA,NA,95.85,95.6,96.14,啦〜啦〜啦)     )

如果有人请求如何处理R编程

1 个答案:

答案 0 :(得分:1)

基于akrun的建议,这是使用cut.POSIXct和dplyr的潜在实现:

library(dplyr)
 output <- 
  sample %>% # Using reproducible dataset above
  # Filter to only observed records
  filter(!is.na(date) & !is.na(time)) %>% 
  mutate(
    # Create a date_time using the date and time variables
    date_time = as.POSIXct(paste(date, time), 
                format="%Y-%m-%d %H:%M"),
    # Create hour intervals to be used as grouping variable 
         hour    = cut.POSIXt(date_time, breaks = "hour")) %>%
  # Group by hour
  group_by(hour) %>%
  # Select only records where the date and time are the minimum
  # date and time in the group
  filter(date_time == min(date_time))

我注释了代码 - 有一些方法可以使代码更简洁和/或更好地处理空记录等边缘情况,但这应该正确选择每小时的最小日期时间。