【问题标题】:Pairwise differences between observations in two groups两组观察值之间的成对差异
【发布时间】:2020-07-13 16:00:43
【问题描述】:

我的数据集中有两个治疗组,我正在寻找一种快速方法来计算第一组和第二组观察结果之间的成对差异。

我怎样才能快速创建所有观察组合并找出它们的差异?

我想我可以像这样使用 expand.grid 来获得主题 ID 的组合...

expand.grid(df$subjectID[df$treatment == 'Active'],
            df$subjectID[df$treatment == 'Placebo'])

然后我可以根据主题 ID 加入结果值并获取它们的差异。如果可以的话,我想要一个更通用的方法。

我基本上是在尝试从头开始计算 Mann-Whitney U 统计量,因此我需要确定活性治疗组的结果值是否大于安慰剂组的结果值 (Y_a - Y_p > 0)。换句话说,我需要将活性治疗组的每个反应与安慰剂治疗组的每个反应进行比较。

所以如果我有一些看起来像这样的数据...

Subject Treatment   Outcome
1       Active      5
2       Active      7
3       Active      6
4       Placebo     2
5       Placebo     1

我要计算差分矩阵...

    S4  S5
S1  5-2 5-1
S2  7-2 7-1
S3  6-2 6-1

以下是一些真实数据:

structure(list(subjectID = c(342L, 833L, 347L, 137L, 111L, 1477L
), treatment = c("CC + TV", "CC + TV", "CC + TV", "Control", 
"Control", "Control"), score_ch = c(2L, 3L, 2L, 3L, 0L, 0L)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

我得到了我想要的结果:

diff_df <- expand.grid('T_ID' = df$subjectID[df$treatment == 'CC + TV'],
            'C_ID' = df$subjectID[df$treatment == 'Control'])

tttt <- diff_df %>%
  left_join(df %>% select(subjectID, score_ch), by = c('T_ID' = 'subjectID')) %>%
  left_join(df %>% select(subjectID, score_ch), by = c('C_ID' = 'subjectID')) %>%
  mutate(val = case_when(score_ch.x == score_ch.y ~ 0.5,
                         score_ch.x > score_ch.y ~ 1,
                         score_ch.x < score_ch.y ~ 0))

但是那种..糟透了..

【问题讨论】:

  • 嗨,Emma,我认为您正在尝试按组进行计算(即 dplyr 的 group_by 或 data.table 的 by = ),但如果没有数据样本就很难判断。你能提供一些dput吗?
  • @IanCampbell 嗨,Ian,我添加了更多细节。希望这会有所帮助。

标签: r pairwise-distance


【解决方案1】:

使用base R outer怎么样?

Result <- outer(df[df$treatment == "Control",3],df[!df$treatment == "Control",3], FUN = '-')
colnames(Result) <- df[df$treatment == "Control","subjectID"]
rownames(Result) <- df[!df$treatment == "Control","subjectID"]
Result
#    137 111 1477
#342   1   0    1
#833  -2  -3   -2
#347  -2  -3   -2

【讨论】:

  • 哦,哇,这似乎太容易了。我试过了,它奏效了!我想保留 ID,但我猜如果我不重新排序矢量,我应该能够正确地重新附加它们。
  • 确实,一些旧的基本 R 函数有些派上用场。我更新了我的答案以包括subjectID
猜你喜欢
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 2015-04-22
  • 2017-05-17
  • 1970-01-01
相关资源
最近更新 更多