我创建了以下函数,它可以找到列与目标的相关性。为此,该函数应用于钻石数据集(这里分配给dt)。
select_variables_gen <- function(variable, target = dt$price, threshold = 0.9){
if(all(class(variable) %in% c("numeric","integer"))){
corr <- abs(cor(variable, target));
if(corr > threshold){
return(T);
}else{F}
}else{F}
};
现在我想应用该函数,但我不知道如何指定函数的参数。这是我试过的
alt_selected_gen <- names(dt)[sapply(dt,
select_variables(variable = dt, target = dt$carat, threshold = 0.1))]
alt_selected_gen;
这将返回一个错误,说第2和第3个参数未被使用。我如何使用函数(使用sapply或其他方式)来指定参数?
我想要的输出是相关度高于阈值的列名。因此,使用上述代码的默认值,将是。
[1] "carat" "price"
你通过了 功能 到 sapply
. 你想通过的是一个 召唤 的功能。
当你使用 sapply
数据框架上的列作为第一个参数被逐一发送给你的函数。如果你想把更多的命名参数传给你的函数,你只需直接把它们作为参数添加到函数的 sapply
在函数本身之后。这是因为点运算符(...
)在 sapply
的形式化参数,它将任何额外的参数传递到你的函数调用中。
因此,它应该只是
names(dt)[sapply(dt, select_variables_gen, target = dt$carat, threshold = 0.1)]
#> [1] "carat" "table" "price" "x" "y" "z"
还请注意,该函数被称为 select_variables_gen
在你的例子中,不是 select_variables
.