代码之家  ›  专栏  ›  技术社区  ›  Alex Coppock

两人一组的优胜者;还是向量值群的变异?

  •  2
  • Alex Coppock  · 技术社区  · 6 年前

    我试着评估一对中的哪个单元是“赢家”。 group_by() %>% mutate() 很接近正确的东西,但不完全正确。特别地

    dat %>% group_by(pair) %>% mutate(winner = ifelse(score[1] > score[2], c(1, 0), c(0, 1))) 不起作用。

    下面的是,但是中间的摘要数据框很笨拙。我们能改进一下吗?

    library(tidyverse)
    set.seed(343)
    # units within pairs get scores
    dat <-
      data_frame(pair = rep(1:3, each = 2),
                 unit = rep(1:2, 3),
                 score = rnorm(6))
    
    # figure out who won in each pair
    summary_df <- 
      dat %>%
      group_by(pair) %>%
      summarize(winner = which.max(score))
    
    # merge back and determine whether each unit won
    dat <- 
      left_join(dat, summary_df, "pair") %>%
      mutate(won = as.numeric(winner == unit))
    dat
    #> # A tibble: 6 x 5
    #>    pair  unit  score winner   won
    #>   <int> <int>  <dbl>  <int> <dbl>
    #> 1     1     1 -1.40       2     0
    #> 2     1     2  0.523      2     1
    #> 3     2     1  0.142      1     1
    #> 4     2     2 -0.847      1     0
    #> 5     3     1 -0.412      1     1
    #> 6     3     2 -1.47       1     0
    

    创建日期:2018-09-26 reprex package (第0.2.0版)。

    可能与 Weird group_by + mutate + which.max behavior

    2 回复  |  直到 6 年前
        1
  •  1
  •   Henrik plannapus    6 年前

    使用 rank

    dat %>% group_by(pair) %>% mutate(won = rank(score) - 1)
    

    更多的乐趣(和略快),使用比较的结果( score[1] > score[2]

    dat %>% group_by(pair) %>%
      mutate(won = c(0, 1, 0)[1:2 + (score[1] > score[2])])
    
        2
  •  2
  •   sbha    6 年前

    dat %>% 
      group_by(pair) %>% 
      mutate(won = score == max(score),
             winner = unit[won == TRUE]) %>% 
       # A tibble: 6 x 5
       # Groups:   pair [3]
       pair  unit  score won   winner
      <int> <int>  <dbl> <lgl>  <int>
    1     1     1 -1.40  FALSE      2
    2     1     2  0.523 TRUE       2
    3     2     1  0.142 TRUE       1
    4     2     2 -0.847 FALSE      1
    5     3     1 -0.412 TRUE       1
    6     3     2 -1.47  FALSE      1