使用 sapply 应用函数时指定参数
Specify arguments when applying function with sapply
我创建了以下函数来查找与目标相关的列。为此,该函数应用于钻石数据集(此处分配给 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;
其中 returns 一个错误,指出第二个和第三个参数未使用。我如何使用函数(通过 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
。
我创建了以下函数来查找与目标相关的列。为此,该函数应用于钻石数据集(此处分配给 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;
其中 returns 一个错误,指出第二个和第三个参数未使用。我如何使用函数(通过 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
。