我正在尝试修改
identify_outliers
包中的 rstatix
函数,以便在确定 is_outlier
函数中的异常值时允许使用任何系数。这是identify_outliers
的代码:
function (data, ..., variable = NULL)
{
is.outlier <- NULL
if (is_grouped_df(data)) {
results <- data %>% doo(identify_outliers, ..., variable = variable)
if (nrow(results) == 0)
results <- as.data.frame(results)
return(results)
}
if (!inherits(data, "data.frame"))
stop("data should be a data frame")
variable <- data %>% get_selected_vars(..., vars = variable)
n.vars <- length(variable)
if (n.vars > 1)
stop("Specify only one variable")
values <- data %>% pull(!!variable)
results <- data %>% mutate(is.outlier = is_outlier(values),
is.extreme = is_extreme(values)) %>% filter(is.outlier ==
TRUE)
if (nrow(results) == 0)
results <- as.data.frame(results)
results
}
这里我通过修改
crazy_outliers
创建了一个名为 identify_outliers
的函数。我删除了与 is_extreme
相关的部分,因为我不需要该部分,并且添加了一个参数 y
以允许将系数输入到 is_outlier
函数中:
crazy_outliers <- function (data, ..., variable = NULL, y) #added y argument
{
is.outlier <- NULL
if (is_grouped_df(data)) {
results <- data %>% doo(crazy_outliers, ..., variable = variable, y = y) # changed identify_outliers to crazy_outliers and added y argument
if (nrow(results) == 0)
results <- as.data.frame(results)
return(results)
}
if (!inherits(data, "data.frame"))
stop("data should be a data frame")
variable <- data %>% get_selected_vars(..., vars = variable)
n.vars <- length(variable)
if (n.vars > 1)
stop("Specify only one variable")
values <- data %>% pull(!!variable)
results <- data %>% mutate(is.outlier = is_outlier(values, coef = y)) #Here I utilize the y argument to specify the coefficient for determining outliers
if (nrow(results) == 0)
results <- as.data.frame(results)
results
}
但是,我在尝试使用该功能时收到以下错误:
Error in `mutate()`:
ℹ In argument: `data = map(.data$data, .f, ...)`.
Caused by error in `map()`:
ℹ In index: 1.
Caused by error in `get_selected_vars()`:
! could not find function "get_selected_vars"
我什至根本没有修改
get_selected_vars()
函数或其参数,它存在于原始 identify_outliers
函数中,所以我对发生的事情感到困惑。我也找不到它来自哪个包,因为当我用 rstatix::get_selected_vars
替换它时,我仍然无法让该功能正常工作。如有任何建议,我们将不胜感激,谢谢!
get_selected_vars
是来自 rstatix
的未导出实用函数。函数可以在包中定义和使用,但除非在命名空间中显式“导出”,否则无法供包的用户使用。您可能是在 R 脚本或笔记本中编写
crazy_outliers
函数,而不是编辑包本身,因此它将无法访问 get_selected_vars
。您可以使用 :::
直接访问它,例如rstatix:::get_selected_vars()
,但这是有风险的,因为包可能会在不经意间改变实用函数的定义方式。或者,您可以内联您自己的函数版本。