【问题标题】:Sorting with date and minimum time in R在R中使用日期和最短时间排序
【发布时间】:2016-12-28 00:41:41
【问题描述】:

这个任务对我来说很难。我需要找到每月 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

类似的示例数据框:

样本

如果有人请帮助如何使用 R 编程

【问题讨论】:

  • 您可以使用cut.POSIXct 将时间缩短为每小时间隔,将其用作分组变量以找到最小值
  • 欢迎来到 StackOverflow!请阅读有关how to ask a good question 的信息以及如何提供reproducible example。这将使其他人更容易帮助您。
  • 感谢@akrun。能详细点吗?
  • Adam 已将其作为解决方案发布

标签: r date time


【解决方案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))

我注释了代码——肯定有办法让代码更简洁和/或更好地处理像空记录这样的边缘情况,但这应该正确选择每小时的最短日期时间。

【讨论】:

  • 谢谢亚当。但我是 R 编程的新手。能否请您详细说明代码,以便我得到完整的结果。 library(dplyr) setwd("C:/Users/Desktop/june") data
  • 没问题。假设这就是您加载非样本数据(作为“数据”)的方式,您需要运行代码以读取文件,然后运行我编写的代码,切换出第三行(“样本 %>%”变成“数据%>%”)
  • library(dplyr) 数据 % filter(!is.na(date) & !is.na (time)) %>% mutate( date_time = as.POSIXct(paste(date, time), format="%Y-%m-%d %H:%M"), hour = cut.POSIXt(date_time, break = "小时")) %>% group_by(hour) %>% filter(date_time == min(date_time))
  • 非常感谢亚当......太棒了
  • > 输出 % + filter(!is.na(Date) & !is.na(Time)) %>% + mutate( + date_time = as.POSIXct(paste (日期,时间),+格式=“%Y-%m-%d %H:%M”),+小时=cut.POSIXt(日期时间,休息=“小时”))%>%+组比(小时) %>% + 过滤器(date_time == min(date_time))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多