2016-12-27 127 views
0

这个任务对我来说很困难。我需要找到每月30/31天每一小时(最短记录时间)的临时值。但是,传感器在不规则的时间段测量温度值(输入文件作为图像附加)。我想为此编写R代码。例如,输出:用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( 日期= C(REP( “2016年6月1日”, (“2016-06-01”,3),NA,NA,代表(“2016-06-01”,3),NA,代表(“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,NA,NA,NA) )

如果请人如何用做帮助[R编程的akrun的建议

+2

您可以使用'cut.POSIXct'将时间缩短为小时间隔,将其用作分组变量以查找最小值 – akrun

+0

欢迎使用StackOverflow!请阅读关于[如何提出一个好问题](http://stackoverflow.com/help/how-to-ask)以及如何给出[可重现的示例]的信息(http://stackoverflow.com/questions/ 5963269)。这会让其他人更容易帮助你。 – Axeman

+0

谢谢@akrun。你能否详细说明一下? –

回答

1

大厦,这里是一个使用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)) 

我注释的代码 - 肯定有办法到m使代码更加简洁和/或更好地处理空记录等边缘案例,但是这应该正确选择每小时的最小日期时间。

+0

感谢Adam。但我是R编程的新手。你能否详细说明代码,以便我能得到完整的结果。库(dplyr) setwd(“C:/ Users/Desktop/june”) data <-read.csv(“test.csv”,stringsAsFactors = FALSE)是否需要在输入文件路径后编写代码。如何用传感器值保存输出...请回复我。 –

+0

没问题。假设这就是你如何加载非样本数据(作为'数据'),你需要运行代码来读取文件,然后运行我编写的代码,将第三行('sample%>%') (!is.na(date))' –

+0

库(dplyr) data < - read.csv(“test.csv”,stringsAsFactors = FALSE) output < - data%>% filter (日期,时间) format =“%Y-%m-%d%H:%M”), 小时= cut.POSIXt(date_time,breaks =“小时”))%>% group_by(小时)%>% 筛选器(date_time == min(date_time)) –