2015-07-20 43 views
0

我有3 columns- START_TIMEEND_TIME能量一个数据帧其中START_TIMEEND_TIME是日期时间格式和能量被能量这两者之间花费时间。 ![输入图片描述] [1]劈裂时间帧到的日期 - [R

我的目标是计算每一天消耗的能量。其中start_timeend_time具有相同日期的实例,能源价值将被分配到该日期。但我需要找到一种方法来分类具有不同日期的能量start_timeend_time。例如,在数据帧一个实例像这个 -

start_time    end_time    energy 
2014-06-09 20:54:10 2014-06-11 05:04:14 1114 

应该产生像这些情况在输出数据帧 -

date  energy 
2014-06-09 <energy consumed between 2014-06-09 20:54:10 to 2014-06-09 23:59:59> 
2014-06-10 <energy consumed between 2014-06-10 00:00:00 to 2014-06-10 23:59:59> 
2014-06-11 <energy consumed between 2014-06-11 00:00:00 to 2014-06-11 05:04:14> 
+0

那么...解释一下你试过的? – hd1

+0

我是R新手,所以尝试了一种非常幼稚的方法,我使用** start_time **并使用** ceiling_date(x,'days')**函数来查找一天结束日期时间。然后添加1秒的偏移量以启动第二天。这样做直到** start_time **和** end_time **的日期相同为止。这将时间戳分成几天。 然后我发现**能量**的比例取决于时间分配给每一天。 想知道是否有更好的方法(库)来处理这个任务,因为它的一些非常基本的东西。 谢谢 –

+0

您只给出了一个示例行。假设后续行不重叠是否安全?例如,2014-06-10第2排可以开始吗?如果是这样的话应该怎么看? –

回答

0

我没有测试它多少(提供的数据框有点稀疏.. ) ,但这似乎工作正常。

calcEnergy <- function(startCol, endCol, valCol) { 
    require(chron) 
    # calculate start and finish times 
    chron.fun <- function(x) chron(x[1], x[2], format=c('y-m-d','h:m:s')) 
    starts <- unlist(lapply(strsplit(as.character(startCol), " "), chron.fun)) 
    ends <- unlist(lapply(strsplit(as.character(endCol), " "), chron.fun)) 
    # need to expand dataframe out to accomodate new rows, so calculate number of 
    # rows per original observation 
    nrows <- ceiling(ends) - floor(starts) 
    # ..& create expanded dataframe based on this 
    df.out <- data.frame(start_time = rep(starts, nrows) + sequence(nrows)-1, 
         end_time = rep.int(ends, nrows) - (rep(nrows,nrows) -sequence(nrows)), 
         valCol = rep.int(valCol, nrows), 
         tDiffs = rep.int(ends - starts, nrows)) 
    # identify non-original starts and finishes (which are unique) 
    startIndex <- !df.out$start_time %in% starts 
    endIndex <- !df.out$end_time %in% ends 
    # floor or ceiling accordingly 
    df.out$start_time[startIndex] <- floor(df.out$start_time[startIndex]) 
    df.out$end_time[endIndex] <- ceiling(df.out$end_time[endIndex]) 
    # calculate proportion energy per day 
    df.out$energy <- with(df.out, valCol*(end_time-start_time)/tDiffs) 
    # reformat cols 
    df.out$date <- chron(floor(df.out$start_time), out.format='y-m-d') 
    df.out[c("date", "energy")] 
}