【问题标题】:Include extra (ellipsis/dot dot dot) arguments within custom function在自定义函数中包含额外的(省略号/点点点)参数
【发布时间】:2021-02-03 20:28:27
【问题描述】:

我正在做一个关于文本挖掘的项目,因此我想编写一个小函数来计算文本中不同标记的数量。标记化由函数tidytext::unnest_token 完成,它基本上是tokenizers::tokenize_ngrams 与管道一起使用的包装器。我目前的做法如下:

count_tokens <- function(data,output,token="words", ...){
  data %>% 
    select(textcolumn) %>% 
    tidytext::unnest_tokens(tbl=output, input=textcolumn, ...) %>% 
    n_distinct()
}

只要我使用来自tidytext::unnest_token 的参数,例如to_lowerdrop,它就可以正常工作(即使使用...)。 count_tokens(data, word, to_lower = FALSE) 工作正常!

现在,tidytext::unnest_token 的文档指出 ... 也可以用作传递给标记器的额外参数,例如 strip_punct 用于“单词”和“推文”,n 和 @ 987654333@ for "ngrams" 和 "skip_ngrams", (...). 但是,如果我在函数的省略号参数中包含参数 n,它会崩溃。

count_tokens(data, ngram, token = "ngrams", to_lower = FALSE, n = 10) 显示以下错误消息:

Error in tf(col, lowercase = to_lower, ...) : unused argument (n = 10)

有人能指出我正确的方向,甚至可以告诉我需要如何调整我的代码吗?

【问题讨论】:

    标签: r ellipsis tidytext


    【解决方案1】:

    首先,您的示例似乎无效。 对我来说,更新后的功能可以正常工作。

    library(dplyr)
    library(tidytext)
    library(janeaustenr)
    
    count_tokens <- function(data,output,token="words", ...){
      d %>% 
        select(txt) %>% 
        tidytext::unnest_tokens(output, input="txt", token = token, ...) %>% 
        n_distinct()
    }
    
    d <- tibble(txt = prideprejudice)
    
    count_tokens(d, "word", to_lower = FALSE)
    #> [1] 6915
    
    count_tokens(d, "ngram", token = "ngrams", to_lower = FALSE, n = 8)
    #> [1] 122189
    
    count_tokens(d, "ngram", token = "ngrams", to_lower = FALSE, n = 5)
    #> [1] 121599
    
    count_tokens(d, "ngram", token = "ngrams", to_lower = FALSE, n = 3)
    #> [1] 104664
    

    reprex package (v0.3.0) 于 2021 年 2 月 3 日创建

    【讨论】:

    • 谢谢你,清除它!由于在没有 n 的情况下包含 token 参数,我没有发现函数中实际上缺少该参数。干杯!
    猜你喜欢
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 2013-09-22
    • 2019-06-06
    • 2023-01-11
    • 2018-11-13
    相关资源
    最近更新 更多