计算R中一组多行之间的差异

Calculate difference between multiple rows by a group in R

我有一个这样的数据框(比这个例子有更多的观察和代码变量):

  code  tmp     wek   sbd
   <chr> <chr> <dbl> <dbl>
 1 abc01 T1        1  7.83
 2 abc01 T1        1  7.83
 3 abc01 T1        2  8.5 
 4 abc01 T1        2  8.5 
 5 abc01 T1        1  7.83
 6 abc01 T1        1  7.83
 7 abc01 T1        1  7.83
 8 abc01 T1        1  7.83
 9 abc01 T1        1  7.83
10 abc01 T2        1  7.56
11 abc01 T2        1  7.56
12 abc01 T2        2  7.22
13 abc01 T2        2  7.22
14 abc01 T2        1  7.56
15 abc01 T2        1  7.56
16 abc01 T2        1  7.56
17 abc01 T2        1  7.56
18 abc01 T2        1  7.56

现在我想计算一个新变量,它通过代码和 tmp 变量给出 wek = 1 和 wek = 2 之间变量 sbd 的差异。

到目前为止,我只是找到了可以区分连续行的函数,但这不适合我的情况。

您可以使用matchwk 1和2处获得相应的sbd值。

library(dplyr)

df %>%
  group_by(code, tmp) %>%
  summarise(diff = sbd[match(1, wek)] - sbd[match(2, wek)])

#  code  tmp    diff
#  <chr> <chr> <dbl>
#1 abc01 T1    -0.67
#2 abc01 T2     0.34

如果要在数据框中添加一个新列以保持行相同,请使用 mutate 而不是 summarise

数据

如果您在 reproducible format

中提供数据,会更容易提供帮助
df <- structure(list(code = c("abc01", "abc01", "abc01", "abc01", "abc01", 
"abc01", "abc01", "abc01", "abc01", "abc01", "abc01", "abc01", 
"abc01", "abc01", "abc01", "abc01", "abc01", "abc01"), tmp = c("T1", 
"T1", "T1", "T1", "T1", "T1", "T1", "T1", "T1", "T2", "T2", "T2", 
"T2", "T2", "T2", "T2", "T2", "T2"), wek = c(1L, 1L, 2L, 2L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), sbd = c(7.83, 
7.83, 8.5, 8.5, 7.83, 7.83, 7.83, 7.83, 7.83, 7.56, 7.56, 7.22, 
7.22, 7.56, 7.56, 7.56, 7.56, 7.56)), 
class = "data.frame", row.names = c(NA, -18L))

使用 distinct 可能有效

df %>%
  group_by(code, tmp) %>%
  distinct() %>%
  summarise(diff = diff(sbd))

  code  tmp    diff
  <chr> <chr> <dbl>
1 abc01 T1     0.67
2 abc01 T2    -0.34