首页 文章

根据指定的时间范围提取并保存为csv文件

提问于
浏览
0

下面是保存为csv文件的数据集示例 . 是否可以提取它们并根据指定的时间范围保存为多个csv文件 .

例如:

指定的时间范围是:

白天:07:30(同一天)至20:30(同一天)夜间:21:30(同一天)至06:30(下一天) .

提取后,数据集将根据此文件名格式保存为csv文件:白天:“date” - day daytime:“date”-night

“date”是时间戳的日期 .

谢谢你的帮助 .

timestamp   c3.1    c3.2    c3.3    c3.4    c3.5    c3.6    c3.7    c3.8    c3.9    c3.10   c3.11   c3.12
8/13/15 15:43   1979.84 1939.6  2005.21 1970    1955.55 1959.82 1989    2001.12 2004.38 1955.75 1958.75 1986.53
8/13/15 15:44   1979.57 1939.64 2005.14 1970.4  1956.43 1958.56 1989.7  2000.78 2004.53 1954.9  1959.76 1986.18
8/13/15 15:45   1979.32 1938.92 2004.52 1970.21 1955.75 1960.12 1989.07 2001.47 2003.7  1955.32 1958.94 1985.79
8/13/15 15:46   1979.33 1939.7  2004.66 1971.25 1955.89 1958.27 1989.24 2000.86 2003.92 1955.29 1959.25 1985.49

1 回答

  • 0

    假设 dat 是您的数据:

    ## The date-time format in the data set
    format <- "%m/%d/%y %H:%M"
    
    ## Convert date-time to POSIXct
    timestamp <- as.POSIXct(dat$timestamp, format = format)
    
    ## First and last dates in the data 
    first <- as.Date(min(timestamp))
    last <- as.Date(max(timestamp)) 
    ## The start of day and night timeframes
    start.day <- paste(first, "07:30")
    start.night <- paste(first - 1, "20:30") ## first night timeframe starts the day before 
    end <- paste(last + 1, "20:30") 
    
    ## The breakpoints, assuming that day is 7:30-20:30 and nigth 20:31-7:29 (i.e. no missing records)
    breaks <- sort.POSIXlt(c(seq.POSIXt(as.POSIXct(start.day), as.POSIXct(end), by= "day"),
                             seq.POSIXt(as.POSIXct(start.night), as.POSIXct(end), by= "day")))
    ## The corresponding labels
    labels <- head(paste0(as.Date(breaks), c("-night", "-day")), - 1)
    
    ## Add column with timeframe
    dat$timeframe <-cut.POSIXt(timestamp, breaks = breaks, labels = labels)
    
    
    ## Save csv files
    for(x in levels(dat$timeframe)) {
      subset <- dat[dat$timeframe == x, ]
      subset$timeframe <- NULL ## Remove the timeframe column
      if(nrow(subset) > 0) write.csv(subset, file = paste0(x, ".csv"))
    }
    

相关问题