gpt4 book ai didi

r - 计算两个或多个时间点的分数变化

转载 作者:行者123 更新时间:2023-12-01 22:47:00 25 4
gpt4 key购买 nike

我有一个非常简单的问题:想象一个有 6 个项目的认知测试,每个项目都在 0-10 的范围内单独评分现在假设有 5 名患者在一天中的三个(或更多)不同时间参加了这项测试。

df <- tibble(
id = rep(1:5, each = 3),
time = rep(c("morning", "evening", "night"), each = 1, times = 5),
i1 = round(runif(15, 0, 10)),
i2 = round(runif(15, 0, 10)),
i3 = round(runif(15, 0, 10)),
i4 = round(runif(15, 0, 10)),
i5 = round(runif(15, 0, 10)),
i6 = round(runif(15, 0, 10))
)

现在,我如何计算一天中不同时间每个患者的每个项目的分数变化?tidyverse 方法受到高度赞赏。

P.S: 输出最好是这样的:

df <- tibble(
id = rep(1:5, each = 3),
time = rep(c("morning", "evening", "night"), each = 1, times = 5),
i1 = round(runif(15, 0, 10)),
i2 = round(runif(15, 0, 10)),
i3 = round(runif(15, 0, 10)),
i4 = round(runif(15, 0, 10)),
i5 = round(runif(15, 0, 10)),
i6 = round(runif(15, 0, 10)),
diff_morning_evening = rep(NA, 15),
diff_morning_night = rep(NA, 15),
diff_evening_night = rep(NA, 15),
)

最佳答案

一种以紧凑方式计算变化的方法:

  • 第一行:早上 - 晚上
  • 第二行:上午 - 晚上
  • 第 3 行:晚上 - 晚上
df %>% 
group_by(id) %>%
mutate(across(i1:i6, ~ ifelse(is.na(.x - lag(.x)),
lead(.x, 2) - .x, .x - lag(.x)),
.names="{.col}_chg")) %>%
ungroup()
# A tibble: 15 × 14
id time i1 i2 i3 i4 i5 i6 i1_chg i2_chg i3_chg i4_chg
<int> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 morning 1 2 4 9 5 6 7 -1 1 -8
2 1 evening 5 0 4 8 9 4 4 -2 0 -1
3 1 night 8 1 5 1 4 5 3 1 1 -7
4 2 morning 7 7 4 3 2 9 -5 -1 4 5
5 2 evening 8 9 1 2 4 5 1 2 -3 -1
6 2 night 2 6 8 8 10 2 -6 -3 7 6
7 3 morning 9 6 6 1 5 5 -8 -1 2 0
8 3 evening 3 2 8 1 3 10 -6 -4 2 0
9 3 night 1 5 8 1 3 3 -2 3 0 0
10 4 morning 7 2 9 1 5 8 1 1 -6 0
11 4 evening 3 5 9 5 6 3 -4 3 0 4
12 4 night 8 3 3 1 3 2 5 -2 -6 -4
13 5 morning 4 1 3 7 1 0 4 6 4 2
14 5 evening 7 2 7 7 5 2 3 1 4 0
15 5 night 8 7 7 9 8 4 1 5 0 2
# … with 2 more variables: i5_chg <dbl>, i6_chg <dbl>

求和特殊行方法

df %>% 
group_by(id) %>%
summarize(across(i1:i6, ~
.x[which(time == "morning")] + .x[which(time == "night")]))
# A tibble: 5 × 7
id i1 i2 i3 i4 i5 i6
<int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 9 3 9 10 9 11
2 2 9 13 12 11 12 11
3 3 10 11 14 2 8 8
4 4 15 5 12 2 8 10
5 5 12 8 10 16 9 4

关于r - 计算两个或多个时间点的分数变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75048630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com