簡體   English   中英

根據每個組的特定行計算 R 中的行之間的差異

[英]Calculate difference between rows in R based on a specifc row for each group

大家好,我有一個 dataframe,其中每個 ID 都有 1-5 的多次訪問。 我正在嘗試計算每次訪問與訪問 1 之間的分數差異。例如。 (分數(訪問 5 分數(訪問 1)等)。我如何在 R 中實現這一點?下面是示例數據集和結果數據集

structure(list(ID = c("A", "A", "A", "A", "A", "B", "B", "B"), 
    Visit = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L), Score = c(16, 
        15, 13, 12, 12, 20, 19, 18)), class = "data.frame", row.names = c(NA, 
    -8L))

#>   ID Visit Score
#> 1  A     1    16
#> 2  A     2    15
#> 3  A     3    13
#> 4  A     4    12
#> 5  A     5    12
#> 6  B     1    20
#> 7  B     2    19
#> 8  B     3    18

代表 package (v2.0.0) 於 2021 年 5 月 20 日創建

這是預期的 output

在此處輸入圖像描述

這是使用dplyr的解決方案

library(dplyr)

df %>% 
  group_by(ID) %>% 
  mutate(Difference = ifelse(Visit == 1, NA, Score[Visit == 1] - Score))

# A tibble: 8 x 4
# Groups:   ID [2]
  ID    Visit Score Difference
  <chr> <int> <dbl>      <dbl>
1 A         1    16         NA
2 A         2    15          1
3 A         3    13          3
4 A         4    12          4
5 A         5    12          4
6 B         1    20         NA
7 B         2    19          1
8 B         3    18          2

樣本數據

df <- data.frame(
  ID = c('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B'),
  Visit = c(1:5, 1:3),
  Score = c(16,15,13,12,12,20,19,18)
)

旁注:下次我建議您不要發布圖像,而是使用 dataframe 上的dput() function 發布示例數據

first使用dplyr的解決方案

data <- data.frame(
  ID = c(rep("A", 5), rep("B", 3)),
  Visit = c(1:5, 1:3),
  Score = c(16, 15, 13, 12, 12, 20, 19, 18))

library(dplyr)
data %>%
  group_by(ID) %>%
  arrange(Visit) %>%
  mutate(Difference = first(Score) - Score)
#> # A tibble: 8 x 4
#> # Groups:   ID [2]
#>   ID    Visit Score Difference
#>   <chr> <int> <dbl>      <dbl>
#> 1 A         1    16          0
#> 2 A         2    15          1
#> 3 A         3    13          3
#> 4 A         4    12          4
#> 5 A         5    12          4
#> 6 B         1    20          0
#> 7 B         2    19          1
#> 8 B         3    18          2

代表 package (v2.0.0) 於 2021 年 5 月 20 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM