Dat*_*iac 6 r data-manipulation dataframe difference dplyr
大家好,我有一个数据框,其中每个 ID 都有 1-5 次多次访问。我正在尝试计算每次访问与访问 1 之间的分数差异。(分数(Visit 5-score(Visit1)等)。我如何在 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
Run Code Online (Sandbox Code Playgroud)
由reprex 包于 2021 年 5 月 20 日创建(v2.0.0)
这是预期的输出
这是一个使用的解决方案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
Run Code Online (Sandbox Code Playgroud)
样本数据
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)
)
Run Code Online (Sandbox Code Playgroud)
旁注:下次我建议您不要发布图像,而是使用dput()数据帧上的函数发布示例数据