【发布时间】:2015-09-13 22:35:15
【问题描述】:
我需要在循环中使用以下函数,因为我有 100 个变量。
binning <- function (df,vars,by=0.1,eout=TRUE,verbose=FALSE) {
for (col in vars) {
breaks <- numeric(0)
if(eout) {
x <- boxplot(df[,col][!df[[col]] %in% boxplot.stats(df[[col]])$out],plot=FALSE)
non_outliers <- df[,col][df[[col]] <= x$stats[5] & df[[col]] >= x$stats[1]]
if (!(min(df[[col]])==min(non_outliers))) {
breaks <- c(breaks, min(df[[col]]))
}
}
breaks <- c(breaks, quantile(if(eout) non_outliers else df[[col]], probs=seq(0,1, by=by)))
if(eout) {
if (!(max(df[[col]])==max(non_outliers))) {
breaks <- c(breaks, max(df[[col]]))
}
}
return (cut(df[[col]],breaks=breaks,include.lowest=TRUE))
}}
它创建一个带有分箱分数的变量。变量命名约定为“原名”加“_bin”。
data$credit_amount_bin <- iv.binning.simple(data,"credit_amount",eout=FALSE)
我希望函数针对所有 NUMERIC 变量运行,并将转换后的 bin 变量存储在不同的数据框中,并用“原始名称 _bin”命名它们。
任何帮助将不胜感激。
【问题讨论】:
标签: r