Reputation: 7832
It is suggested, that function calls inside R-package functions should preferably use standard evaluation (see here), especially to avoid utils::globalVariables
.
If I'm using non-standard evaluation with the dplyr package, what would be the "translation" into standard evaluation for the following code-snippet - especially for the table
-command?
grp
and dep
are numeric values of the data frame mydf
, while x
is a factor.
Non-standard evaluation:
pvals <- mydf %>%
dplyr::group_by(grp) %>%
dplyr::summarise(N = n(),
p = suppressWarnings(stats::chisq.test(table(x, dep))$p.value))
Standard evaluation?
pvals <- mydf %>%
dplyr::group_by_("grp") %>%
dplyr::summarise_(N = n(),
p = suppressWarnings(stats::chisq.test(table("x", "dep"))$p.value))
And, what about function calls with ggplot
? Does ggplot
have standard-evaluation support?
Edit: Added reproducible example.
library(dplyr)
data(ChickWeight)
ChickWeight %>%
dplyr::group_by(Diet) %>%
dplyr::summarise(N = n(),
p = suppressWarnings(stats::chisq.test(table(weight, Time))$p.value))
Upvotes: 2
Views: 318
Reputation: 2151
You can try to never hard code the variable names within your function, and use rlang
quasiquotation instead.
From your example, within a function context, I would write :
#' Chisq table
#' @importFrom rlang enquo !!
#' @importFrom magrittr %>%
#'
#' @param data Dataset
#' @param x,y,group bare variable names
#' @export
chisq_table <- function(data, x, y, group){
x <- enquo(x)
y <- enquo(y)
group <- enquo(group)
data %>%
dplyr::group_by(!!group) %>%
dplyr::summarise(
N = dplyr::n(),
p = suppressWarnings(stats::chisq.test(table(!!x, !!y))$p.value)
)
}
data(ChickWeight)
chisq_table(data = ChickWeight, x = weight, y = Time, group = Diet)
## # A tibble: 4 x 3
## Diet N p
## <fct> <int> <dbl>
## 1 1 220 4.42e-16
## 2 2 120 3.76e- 7
## 3 3 120 4.74e- 6
## 4 4 118 1.33e- 5
This does not trigger a note when checking the package, and makes maintaining your functions easier if the column names in your datasets happen to change.
Upvotes: 1
Reputation: 663
If you wan't to use dplyr I would just ignore the false positive of the codetools::checkUsagePackage().
Upvotes: 0