I have a data table called data:
[![This is a screengrab of the data table][1]][1]
The goal is to write a function that mimics the following code:
data[Region == "Northeast",mean(Awareness, na.rm = TRUE), by = Product][order(-rank(V1))][1:5,.(Product)]
So far I have:
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)]
}
The function topx_engagement should allow a user to enter respondent_variable which coincides with Region, a respondent_variable_sub which coincides with "Northeast" and subsequent arguments. I would like to focus on the preceding arguments as all the other work fine.
Currently, when I call:
topx_engagement(state_of_engagement = Awareness, respondent_variable = Region, respondent_variable_sub = Northeast, rank_length = 3)
I get an error:
Error in topx_engagement(state_of_engagement = Awareness, respondent_variable = Region, : object 'Northeast' not found
Alternately, running
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)
throws an error of Error in eval(.massagei(isub[[2L]]), parent.frame(), parent.frame()) : object 'Region' not found
I need assistance with getting the function inputs in the right format. [1]: https://i.sstatic.net/hseWS.png
We may use deparse/substitute
to convert to character
string if we are passing unquote arguments
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)]
}
then call it as
topx_engagement(state_of_engagement = Awareness,
respondent_variable = Region,
respondent_variable_sub = Northeast, rank_length = 3)