我陷入了一项相当简单的数据处理任务。我在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中保留上一个日期
发布评论