在R中保留上一个日期

编程入门 行业动态 更新时间:2024-10-23 11:16:18
本文介绍了在R中保留上一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我陷入了一项相当简单的数据处理任务。我在R中有一个与此类似的交易数据框:

I got stuck at a fairly easy data munging task. I have a transactional data frame in R that resembles this one:

id<-c(11,11,22,22,22) dates<-as.Date(c('2013-11-15','2013-11-16','2013-11-15','2013-11-16','2013-11-17'), "%Y-%m-%d") example<-data.frame(id=id,dates=dates) id dates 1 11 2013-11-15 2 11 2013-11-16 3 22 2013-11-15 4 22 2013-11-16 5 22 2013-11-17

我正在寻找一种保留上次交易日期的方法。结果表如下所示:

I'm looking for a way to retain the date of the previous transaction. The resulting table would look like this:

previous_dates<-as.Date(c('','2013-11-15','','2013-11-15','2013-11-16'), "%Y-%m-%d") example2<-data.frame(id=id,dates=dates, previous_dates=previous_dates) id dates previous_dates 1 11 2013-11-15 <NA> 2 11 2013-11-16 2013-11-15 3 22 2013-11-15 <NA> 4 22 2013-11-16 2013-11-15 5 22 2013-11-17 2013-11-16

我调查了其他类似的问题,并且一个非常接近我想要的解决方案是:

I looked into other similar problems and one solution that is very close to what I want is:

library(data.table) dt <- as.data.table(example) prev_date <- function(x) c(x[1],x) dt[,prev:=prev_date(dates), by=id]

此问题的原因是,如果没有先前的日期(例如id = 11 date = 2013-11-15 的情况下,),该函数将输出相同的日期,从而导致:

The problem with this one is that if there is no previous date (like in the case of id=11 dates=2013-11-15) the function would output the same date resulting in:

id dates previous_dates 1 11 2013-11-15 2013-11-15 2 11 2013-11-16 2013-11-15

有人可以帮忙吗?

推荐答案

example$previous_dates <- ave(example$dates, example$id, FUN= function(dt) c.Date( c(NA, dt[-length(dt)]) )) > example id dates previous_dates 1 11 2013-11-15 <NA> 2 11 2013-11-16 2013-11-15 3 22 2013-11-15 <NA> 4 22 2013-11-16 2013-11-15 5 22 2013-11-17 2013-11-16

播放Date对象的类....这也可以:

Playing around with the classes of Date objects .... this also works:

example$previous_dates <- ave(example$dates, example$id, FUN= function(dt) structure( c(NA, dt[-length(dt)]), class="Date" ) )

更多推荐

在R中保留上一个日期

本文发布于:2023-10-23 02:04:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!