我没有测试它多少(提供的数据框有点稀疏.. ) ,但这似乎工作正常。
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")]
}
那么...解释一下你试过的? – hd1
我是R新手,所以尝试了一种非常幼稚的方法,我使用** start_time **并使用** ceiling_date(x,'days')**函数来查找一天结束日期时间。然后添加1秒的偏移量以启动第二天。这样做直到** start_time **和** end_time **的日期相同为止。这将时间戳分成几天。 然后我发现**能量**的比例取决于时间分配给每一天。 想知道是否有更好的方法(库)来处理这个任务,因为它的一些非常基本的东西。 谢谢 –
您只给出了一个示例行。假设后续行不重叠是否安全?例如,2014-06-10第2排可以开始吗?如果是这样的话应该怎么看? –