【问题标题】:Why doesn't rev(factor) work as a way to reverse the wt argument of dplyr::top_n()?为什么 rev(factor) 不能作为反转 dplyr::top_n() 的 wt 参数的一种方式?
【发布时间】:2020-12-17 00:30:43
【问题描述】:

目标:返回 thing1=F 和 thing2=MeFirst 的行

为什么这不起作用?

tibble(
    row = 1:10,
    thing1 = c(rep("F",5),rep("L",5)),
    thing2 = c(rep("MeSecond",4),rep("MeFirst",2),rep("MeSecond",4))
) %>%
    mutate(
        thing1 = factor(thing1, levels = c("F", "L")),
        thing2 = factor(thing2, levels = c("MeFirst", "MeSecond"))
    ) %>%
    top_n(
        .,
        n = 1,
        wt = rev(thing1)
    ) %>%
    top_n(
        .,
        n = 1,
        wt = rev(thing2)
    )

以上返回行 2:5。

我知道这确实有效:

tibble(
    row = 1:10,
    thing1 = c(rep("F",5),rep("L",5)),
    thing2 = c(rep("MeSecond",4),rep("MeFirst",2),rep("MeSecond",4))
) %>%
    mutate(
        thing1 = factor(thing1, levels = c("F", "L")),
        thing2 = factor(thing2, levels = c("MeFirst", "MeSecond"))
    ) %>%
    top_n(
        .,
        n = -1,
        wt = thing1
    ) %>%
    top_n(
        .,
        n = -1,
        wt = thing2
    )

但问题是,为什么 rev(thing2) 不起作用?

【问题讨论】:

    标签: r dplyr tidyverse top-n


    【解决方案1】:

    简短的回答是您想要反转因子的水平,而不是因子本身:

    library(dplyr)
    library(forcats)
    
    tibble(row = 1:10,
           thing1 = c(rep("F", 5), rep("L", 5)),
           thing2 = c(rep("MeSecond", 4), rep("MeFirst", 2), rep("MeSecond", 4))) %>%
      mutate(thing1 = factor(thing1, levels = c("F", "L")),
             thing2 = factor(thing2, levels = c("MeFirst", "MeSecond"))) %>%
      top_n(n = 1, wt = fct_rev(thing1)) %>%
      top_n(n = 1, wt = fct_rev(thing2))
    
    # A tibble: 1 x 3
        row thing1 thing2 
      <int> <fct>  <fct>  
    1     5 F      MeFirst
    

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2015-05-08
      • 2021-04-12
      • 2013-11-19
      • 2021-05-22
      • 1970-01-01
      相关资源
      最近更新 更多