R数据表中的计算时间增量 [英] Compute Time Delta in R data.table

查看:74
本文介绍了R数据表中的计算时间增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个篮球运动员数据的数据表,包括每个游戏和多个玩家的游戏日期。我想创建一个计算自上次游戏以来的天数的列。我在R中使用data.table包。

I have a data table of basketball player data which includes the game date for each game and multiple players. I want to create a column that computes the number of days since the previous game. I'm using the data.table package in R.

   PLAYERID GAME_DATE
1:     2989 2014-01-1
2:     2989 2014-01-3

我使用下面的代码: / p>

I'm using the following code:

DT[, DAY_DIFF:=diff(GAME_DATE, lag=1), by=PLAYERID]

它返回:

   PLAYERID GAME_DATE DAY_DIFF
1:     2989 2014-01-1 2
2:     2989 2014-01-3 2

其中它追加除了最后一行之外的每一行的下一个游戏的天数。在最后一行,它追加自上次游戏以来的天数,我想要的值。我想在第一行放一个NA,因为它是第一个游戏。

where it appends the number of days until the next game for every row except the last. In the last row, it appends the number of days since the previous game, the value I want. I want to put an NA in the first row because it is the first game.

推荐答案

# Reproduce the data.table
DT <- fread("PLAYERID GAME_DATE\n2989 2014-01-1\n2989 2014-01-3")
DT[, GAME_DATE:=as.Date(GAME_DATE)]

# concatenate an NA to the front and use na.pad=FALSE with diff()
DT[, DAY_DIFF:=c(NA, diff(GAME_DATE, lag=1, na.pad=FALSE)), by=PLAYERID]
DT
#    PLAYERID  GAME_DATE DAY_DIFF
# 1:     2989 2014-01-01       NA
# 2:     2989 2014-01-03        2

这篇关于R数据表中的计算时间增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆