【问题标题】:Spliting time frames into dates R将时间框架拆分为日期 R
【发布时间】:2015-07-20 20:54:53
【问题描述】:

我有一个包含 3 列的数据框 - start_timeend_timeenergy 其中 start_time end_time 是日期时间格式,energy 是这两个时间之间消耗的能量。 ![在此处输入图片说明][1]

我的目标是计算每天消耗的能量。 start_timeend_time 具有相同日期的实例,energy 值将分配给该日期。但我需要找到一种方法来对 start_timeend_time 具有不同日期的 energy 值进行分类。例如像这样的数据框中的一个实例-

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>

【问题讨论】:

  • 那么...解释一下你尝试了什么?
  • 我是 R 新手,所以尝试了一种非常幼稚的方法,我采用了 start_time 并使用了 ceiling_date(x, 'days')函数查找一天的结束日期时间。然后为其添加 1 秒的偏移量以开始第二天。这样做直到 start_timeend_time 的日期相同。这将时间戳分成了几天。然后我找到了根据时间分配给每一天的能量的比例。想知道是否有更好的方法(库)来处理这个任务,因为它是一些非常基本的东西。谢谢
  • 您只给出了一个示例行。假设后续行不重叠是否安全?例如,第 2 行可以从 2014 年 6 月 10 日开始吗?如果是这样,那应该怎么看?
  • 是的,假设时间不重叠是安全的。它们可能在同一日期,但小时或分钟或秒会不同
  • stackoverflow.com/questions/13912282/… 希望对您有所帮助,Zeeshan

标签: r date


【解决方案1】:

我没有测试太多(提供的数据帧有点稀疏..) ,但这似乎可以正常工作。

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")]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2013-10-18
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多