【问题标题】:Weight variable in dplyr top_ndplyr top_n 中的权重变量
【发布时间】:2014-09-19 08:39:08
【问题描述】:

我正在尝试使用包dplyr 中的top_n 函数,但只有当我让函数使用默认权重(数据框中的最后一个变量)时,它似乎才有效。以下示例(使用默认权重)有效:

library(babynames)
ba <- babynames
ba %>% filter(year == 2013) %>% group_by(sex) %>% top_n(n = 5)

Selecting by prop
Source: local data frame [10 x 5]

但是,这些不是:

ba %>% filter(year == 2013) %>% group_by(sex) %>% top_n(n = 5, wt = "prop")
Source: local data frame [33,072 x 5]

ba %>% filter(year == 2013) %>% group_by(sex) %>% top_n(n = 5, wt = prop)
Error in top_n(`ba %>% filter(year == 2013) %>% group_by(sex)`, n = 5,  : 
  object 'prop' not found

【问题讨论】:

标签: r dplyr


【解决方案1】:

这似乎是一个错误。请提交错误报告。这是一个似乎可以按预期工作的更正版本。

top_n <- function (x, n, wt = NULL) 
{
  wt <- substitute(wt) # new line to correct is.null(wt)
  if (is.null(wt)) {
    vars <- tbl_vars(x)
    message("Selecting by ", vars[length(vars)])
    wt <- as.name(vars[length(vars)])
  }
  call <- substitute(filter(x, rank(desc(wt), ties.method = "min") <= 
                              n), list(n = n, wt = substitute(wt)))
  eval(call)
}

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2020-12-26
    • 1970-01-01
    • 2019-06-08
    • 2017-01-15
    • 2016-07-20
    • 1970-01-01
    • 2016-12-03
    • 2018-07-10
    相关资源
    最近更新 更多