【问题标题】:Find Maximum value and ties based on different criteria根据不同的标准查找最大值和关系
【发布时间】:2019-03-04 17:18:58
【问题描述】:

对于我的变量simulation 和iteration 的每个组合,我想

  • 找出group "a"是否也有rand1的最大值 作为rand2,
  • 知道group "a"是否与基于rand1的另一个组绑定,以及rand2

一些示例 df(带有硬编码值 rand1 和 rand2 以实现可重复性:

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.crit2 和 ties.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

到目前为止,这是我的代码,仅用于确定最大值(但不考虑平局),单独确定 rand1 和 rand2 的最大值有点繁琐。

  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)

【问题讨论】:

  • 您能否提供一个可重现的示例?由于您没有提供 set.seed 值,因此我们无法重现您所显示的 df 数据框

标签: r


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2021-04-12
    • 2020-03-21
    相关资源
    最近更新 更多