如何让我的函数参数成为 r 中数据表的正确类型?

How can i get my function arguments to be of the corrct type for datatables in r?

我有一个数据 table 叫做 data:

[![这是数据的屏幕截图 table][1]][1]

目标是编写一个模仿以下代码的函数:

data[Region == "Northeast",mean(Awareness, na.rm = TRUE), by = Product][order(-rank(V1))][1:5,.(Product)]

到目前为止我有:

topx_engagement = function(state_of_engagement, respondent_variable, respondent_variable_sub, rank_length = 3){
  
  respondent_variable_sub = as.character(respondent_variable_sub)
  
  data[eval(respondent_variable == respondent_variable_sub), mean(get(state_of_engagement), na.rm = TRUE), by = Product][order(-rank(V1))][1:rank_length,.(Product)]
}

函数 topx_engagement 应该允许用户输入 respondent_variable 这与 Region,一个respondent_variable_sub"Northeast"及后续参数重合。我想专注于前面的参数,因为所有其他参数都很好。

目前,当我打电话时:

topx_engagement(state_of_engagement = Awareness, respondent_variable = Region, respondent_variable_sub = Northeast, rank_length = 3)

我得到一个错误:

错误 topx_engagement(state_of_engagement = 意识,respondent_variable = 区域,: 找不到对象 'Northeast'

或者,运行

topx_engagement = function(state_of_engagement, respondent_variable, respondent_variable_sub, rank_length = 3){
  
  #respondent_variable_sub = as.character(respondent_variable_sub)
  
  data[eval(respondent_variable == respondent_variable_sub), mean(get(state_of_engagement), na.rm = TRUE), by = Product][order(-rank(V1))][1:rank_length,.(Product)]
}

topx_engagement(state_of_engagement = Awareness, respondent_variable = Region, respondent_variable_sub = Northeast, rank_length = 3)

抛出错误 Error in eval(.massagei(isub[[2L]]), parent.frame(), parent.frame()) : object 'Region' 未找到

我需要帮助以正确的格式获取函数输入。 [1]: https://i.stack.imgur.com/hseWS.png

如果我们传递不加引号的参数,我们可以使用 deparse/substitute 转换为 character 字符串

topx_engagement = function(state_of_engagement, 
     respondent_variable, respondent_variable_sub, rank_length = 3){
  
  state_of_engagement <- deparse(substitute(state_of_engagement))
  respondent_variable <- deparse(substitute(respondent_variable))
  respondent_variable_sub <- deparse(substitute(respondent_variable_sub))
 
 
  
  
  data[eval(as.name(respondent_variable)) == respondent_variable_sub, 
        mean(get(state_of_engagement), na.rm = TRUE), 
           by = Product][order(-rank(V1))][1:rank_length,.(Product)]
}

然后称它为

topx_engagement(state_of_engagement = Awareness, 
   respondent_variable = Region, 
       respondent_variable_sub = Northeast, rank_length = 3)