2016-12-27 77 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)) –