根据不同条件查找最大值和联系

时间:2019-03-04 17:18:58

标签: r

对于变量simulationiteration的每种组合,我想

  • 确定group "a"是否也具有rand1的最高值 为rand2
  • 了解group "a"是否与基于rand1的另一组以及rand2绑定

某些样本df(具有rand1rand2的硬编码值,以提高可重复性:

df = crossing(simulation = 1:3,
              iteration = 1:3, 
              group =c("a","b","c")) %>%
mutate(rand1 = c(6,2,2,6,4,6, sample(6,21,replace=T)), # roundabout way to get the same head of df as in the example, forgot to use set.seed
       rand2 = c(4,1,2,5,6,1,sample(6,21,replace=T)))

给出:

 simulation iteration group    rand1 rand2
          1         1 a            6     4
          1         1 b            2     1
          1         1 c            2     2
          1         2 a            6     5
          1         2 b            4     6
          1         2 c            6     1

这就是我希望输出的样子:top.crit1如果a组最大,则为1,如果有平局,则为0。 ties.crit1让我知道a是否与另一个组绑定了最大值,与top.crit2ties.crit2相同(以下未添加以避免混乱) 所需的输出:

 simulation iteration group    rand1 rand2  top.crit1 ties.crit1 
          1         1 a            6     4  1         0
          1         1 b            2     1  1         0
          1         1 c            2     2  1         0
          1         2 a            6     5  0         1
          1         2 b            4     6  0         1
          1         2 c            6     1  0         1

到目前为止,这是我的代码,仅用于确定最大值(但不考虑关系),分别确定rand1rand2的最大值有点繁琐。

  df.test = df %>%
  group_by(simulation, iteration) %>% 
  slice(which.max(rand1)) %>% 
  mutate(top.crit1 = if_else(group=="a",1,0)) %>% 
  select(-rand2, -rand1, -group) %>% 
  full_join(., df)

1 个答案:

答案 0 :(得分:1)

如果您arrange将组a作为每个组的第一行,这将起作用

df %>% group_by(simulation, iteration) %>% mutate(top.crit1 = rand1[1] > max(rand1[-1])) %>% mutate(ties.crit1 = rand1[1] == max(rand1[-1]))