【问题标题】:How does `fct_reorder2` compute this result?`fct_reorder2` 如何计算这个结果?
【发布时间】:2021-10-03 14:32:34
【问题描述】:

尽管咨询了this 线程,但我很难理解以下输出:

df <- tibble::tribble(
  ~color,     ~a, ~b,
  "blue",      1,  2,
  "green",     6,  2,
  "purple",    3,  3,
  "red",       2,  3,
  "yellow",    5,  1
)

这给出了:

> fct_reorder2(df$color, df$a, df$b, .fun = min, .desc = TRUE)
[1] blue   green  purple red    yellow
Levels: purple green red blue yellow

我知道您应该以不同的方式使用 .funfct_reorder2。这里的min 函数计算所有提供值的最小值,这里是df$adf$b 中的值。我仍然不会期望我得到的结果。有人可以解释一下吗?

【问题讨论】:

    标签: r tidyverse forcats


    【解决方案1】:

    其中一个链接答案因查看源代码而被否决,但您询问的是如何做的,所以我认为实际查看 fct_reorder2 的代码是有意义的。

    # This is fine, just checking if it's a factor and assigning the value.
    f <- check_factor(.f)
    # Also fine, they're columns from a data.frame
    stopifnot(length(f) == length(.x), length(.x) == length(.y))
    # We're not using dots
    ellipsis::check_dots_used()
    

    这样我们就可以将后续代码与原始数据一起使用:

    summary <- tapply(seq_along(.x), f, function(i) .fun(.x[i], .y[i], ...))
    # for us equivalent to
    tapply(seq_along(df$a), df$color, function(i) {min(df$a[i], df$b[i])})
    #   blue  green purple    red yellow 
    #     1      2      3      2      1 
    

    在这种情况下,这只是列 df$adf$b 的成对最小值 如果每种颜色有多行,它将使用因子级别的任何行或列中的最小值。

    lvls_reorder(.f, order(summary, decreasing = .desc))
    

    这只是根据这些值按降序排列级别,因此首先是列 a 和 b 的 最大 成对最小值的颜色。 在平局的情况下,我们可以看到它是按字典顺序排序的,从而导致我们看到的输出。

    color a b pmin dense rank descending order
    (Lexicographically sorted for ties)
    blue 1 2 1 1 4
    green 6 2 2 2 2
    purple 3 3 3 3 1
    red 2 3 2 2 3
    yellow 5 1 1 1 5

    【讨论】:

      【解决方案2】:
      df <- tibble::tribble(
        ~color,     ~a, ~b,
        "blue",      1,  2,
        "green",     6,  2,
        "purple",    3,  3,
        "red",       2,  3,
        "yellow",    5,  1
      )
      
      df %>% mutate(
        nr = 1:5,
        min = ifelse(a<=b, a, b)
      ) %>% arrange(desc(min), nr) 
      

      输出

      # A tibble: 5 x 5
        color      a     b    nr   min
        <chr>  <dbl> <dbl> <int> <dbl>
      1 purple     3     3     3     3
      2 green      6     2     2     2
      3 red        2     3     4     2
      4 blue       1     2     1     1
      5 yellow     5     1     5     1
      

      这应该可以解决所有问题。

      【讨论】:

      • 这并不完全一样。例如,将黄色行放在第一个而不是最后一个,fct_reorder2 仍将保持相同的顺序,因为字典顺序中断,您的输出会更改,因为它按出现顺序中断。
      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 2023-02-07
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多