【问题标题】:Passing column names as both variables and columns in a single dplyr function in R在R中的单个dplyr函数中将列名作为变量和列传递
【发布时间】:2018-02-05 18:13:12
【问题描述】:

我正在编写一个代码,其中列名(例如"Category")由用户提供并分配给变量biz.area。比如……

biz.area <- "Category"

原始数据框保存为risk.data。用户还通过为变量first.columnlast.column 提供列名来提供要分析的列范围。

这些列中的文本将被分解为二元组,以进行进一步的文本分析,包括 tf_idf。

我的分析代码如下。

x.bigrams <- risk.data %>% 
  gather(fields, alldata, first.column:last.column) %>% 
  unnest_tokens(bigrams,alldata,token = "ngrams", n=2) %>% 
  count(bigrams, biz.area, sort=TRUE) %>%
  bind_tf_idf(bigrams, biz.area, n) %>%
  arrange(desc(tf_idf))

但是,我收到以下错误。

grouped_df_impl(data, unname(vars), drop) 中的错误:列 x.biz.area 未知

这是因为count() 需要一个列名文本字符串,而不是变量biz.area。如果我改用count_(),我会收到以下错误。

compat_lazy_dots(vars, caller_env()) 中的错误:对象 'bigrams' 没找到

这是因为count_() 只希望找到变量,而bigrams 不是变量。

如何将常量和变量同时传递给count()count_()

感谢您的建议!

【问题讨论】:

  • 您能否提供一些示例数据(使用dput() 等)以及您想要作为最终输出的内容?

标签: r dataframe count dplyr


【解决方案1】:

在我看来,您需要使用附件,这样您就可以将列名作为变量传递,而不是作为字符串或值传递。由于您已经在使用 dplyr,您可以使用dplyr's non-standard evaluation techniques

尝试以下方法:

library(tidyverse)

analyze_risk  <- function(area, firstcol, lastcol) {

    # turn your arguments into enclosures
    areaq  <- enquo(area)
    firstcolq <- enquo(firstcol)
    lastcolq <- enquo(lastcol)

    # run your analysis on the risk data
    risk.data %>% 
      gather(fields, alldata, !!firstcolq:!!lastcolq) %>% 
      unnest_tokens(bigrams,alldata,token = "ngrams", n=2) %>% 
      count(bigrams, !!areaq, sort=TRUE) %>%
      bind_tf_idf(bigrams, !!areaq, n) %>%
      arrange(desc(tf_idf))
}

在这种情况下,您的用户会将裸列名称传递给函数,如下所示:

myresults  <- analyze_risk(Category, Name_of_Firstcol, Name_of_Lastcol)

如果您希望用户传入字符串,则需要使用 rlang::expr() 而不是 enquo()

【讨论】:

    猜你喜欢
    • 2015-11-21
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2020-01-13
    • 2015-05-12
    • 2015-03-29
    相关资源
    最近更新 更多