简体   繁体   English

两组观察值之间的成对差异

[英]Pairwise differences between observations in two groups

I have two treatment groups in my data set and I am looking for a fast method for calculating the pairwise differences between observations in the first group and second group.我的数据集中有两个治疗组,我正在寻找一种快速方法来计算第一组和第二组观察值之间的成对差异。

How can I quickly create all the combinations of observations and take their difference?如何快速创建所有观察组合并取其差异?

I think I might be able to get combinations of the subject ids by using expand.grid like so...我想我可以像这样使用 expand.grid 来获得主题 ID 的组合......

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

and then I could join the outcome values based on subject ID and take their difference.然后我可以根据主题 ID 加入结果值并计算它们的差异。 I'd like a more generalized approach though if it is available.如果可以的话,我想要一种更通用的方法。

I'm basically trying to calculate the Mann-Whitney U statistic from scratch so I need to determine if an outcome value in the active treatment group is greater than the outcome value in the placebo group (Y_a - Y_p > 0).我基本上是在尝试从头开始计算 Mann-Whitney U 统计量,因此我需要确定积极治疗组的结果值是否大于安慰剂组的结果值(Y_a - Y_p > 0)。 In other words, I need to compare every response in the active treatment group to every response in the placebo treatment group.换句话说,我需要将积极治疗组中的每个反应与安慰剂治疗组中的每个反应进行比较。

So if I have some data that looks like this...所以如果我有一些看起来像这样的数据......

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

I want to calculate the difference matrix...我想计算差分矩阵...

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

Here's some real data:下面是一些真实数据:

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"))

I got the results that I wanted via:我通过以下方式得到了我想要的结果:

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))

But that kind of.. sucks..但那种..糟透了..

How about with base R outer ?基础 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM