按组从上一行中减去日期(使用R) [英] Substract date from previous row by group (using R)

查看:90
本文介绍了按组从上一行中减去日期(使用R)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此有类似的问题(

I'm having a similar question to this one (subtract value from previous row by group), but I want to subtract the previous date from the current date, by group ID in order to have an estimated number of days. I tried editing the scripts suggesed previously by replacing "value" by "date". Although I tried different suggested methods, but i keep getting this error message "Error in mutate_impl(.data, dots) : Evaluation error: unable to find an inherited method for function first for signature "POSIXct"."

Data
id      date        
2380    10/30/12    
2380    10/31/12    
2380    11/1/12     
2380    11/2/12     
20100   10/30/12    
20100   10/31/12   
20100   11/1/12     
20100   11/2/12     
20103   10/30/12

我想要一张这样的桌子

Data
id      date        date_difference(in days)
2380    10/30/12    0
2380    10/31/12    1
2380    11/1/12     2
2380    11/2/12     3
20100   10/30/12    0
20100   10/31/12    2
20100   11/1/12     3
20100   11/2/12     4
20103   10/30/12    0
20103   10/31/12    1

推荐答案

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

df <- tribble(~id,      ~date,      
2380,    "10/30/12",    
2380,   "10/31/12",    
2380,  "11/1/12",  
2380,    "11/2/12",  
20100,   "10/30/12",    
20100,   "10/31/12",   
20100,   "11/1/12",   
20100,   "11/2/12",   
20103,   "10/30/12",
20103,   "10/31/12")

df %>% 
  mutate(date = mdy(date)) %>% 
  group_by(id) %>% 
  mutate(date_difference = as.numeric(date - first(date)))
#> # A tibble: 10 x 3
#> # Groups:   id [3]
#>       id date       date_difference
#>    <dbl> <date>               <dbl>
#>  1  2380 2012-10-30               0
#>  2  2380 2012-10-31               1
#>  3  2380 2012-11-01               2
#>  4  2380 2012-11-02               3
#>  5 20100 2012-10-30               0
#>  6 20100 2012-10-31               1
#>  7 20100 2012-11-01               2
#>  8 20100 2012-11-02               3
#>  9 20103 2012-10-30               0
#> 10 20103 2012-10-31               1

reprex软件包(v0.2.1)于2018-11-29创建 sup>

Created on 2018-11-29 by the reprex package (v0.2.1)

这篇关于按组从上一行中减去日期(使用R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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