使用 dplyr::lag 计算行之间的差异后保留第一行

keep first row after calculating difference between rows with dplyr::lag

我的问题与此类似 and this ,有一点不同似乎过于复杂。

我的数据示例:

ind_id   wt   date
1002     25   1987-07-27
1002     15   1988-05-05
2340     30   1987-03-18
2340     52   1989-08-15

我正在计算 group_by(ind_id) 之后的 wt 个值之间的差异。

为此:

df<-df %>% 
    group_by(ind_id) %>%
    mutate(mass_diff=(wt-lag(wt)) 

这给了我这个输出:

ind_id   wt   date        mass_diff
1002     15   1988-05-05  -10
2340     52   1989-08-15  22

但是,我想要的输出应该保留 第一个 wt 个记录,而不是最后一个。

期望的输出:

ind_id   wt   date        mass_diff
1002     25   1988-05-05  -10
2340     30   1989-08-15  22

请注意,wt 列是我希望从第一行开始保留的唯一一列。 (请记住,此示例过于简化,我实际上使用的是 18 行)。

任何建议(使用 dplyr)将不胜感激!

可能的解决方案:

library(tidyverse)

df <- structure(list(ind_id = c(1002, 1002, 2340, 2340), wt = c(25, 
15, 30, 52), date = structure(c(6416, 6699, 6285, 7166), class = "Date")), row.names = c(NA, 
-4L), class = "data.frame")

df %>% 
  group_by(ind_id) %>%
  mutate(mass_diff = (wt-lag(wt))) %>% 
  mutate(wt = first(wt)) %>% 
  slice_tail %>% ungroup

#> # A tibble: 2 × 4
#>   ind_id    wt date       mass_diff
#>    <dbl> <dbl> <date>         <dbl>
#> 1   1002    25 1988-05-05       -10
#> 2   2340    30 1989-08-15        22