How to use a for loop with a function requiring a string for a field?

I use the smbinning R package to calculate the value of the variable information included in my dataset.

The smbinning() function is quite simple and should be used as follows:

 result = smbinning(df= dataframe, y= "target_variable", x="characteristic_variable", p = 0.05) 

So, df is the data set that you want to analyze, y target variable and x is the variable from which you want to compute statistics of information values; I list all the characteristic variables as z1, z2, ... z417 in order to be able to use the for loop to mechanize the entire analysis process.

I tried using the following for a loop:

 for (i in 1:417) { result = smbinning(df=DATA, y = "FLAG", x = "DATA[,i]", p=0.05) } 

in order to be able to calculate the information value for each variable corresponding to column i of the data frame.

The DATA class is "data.frame" and the result is "character" .

So my question is how to calculate the value of the information for each variable and store it in the declared result object?

Thanks! Any help would be appreciated!

+8
for-loop r statistics binning
source share
2 answers

No sample data can be dangerous. I can only fear that the following will work:

 results_list = list() for (i in 1:417) { current_var = paste0('z', i) current_result = smbinning(df=DATA, y = "FLAG", x = current_var, p=0.05) results_list[i] = current_result$iv } 
+6
source share

You can try using one of the apply methods, iterating over z-counts. The x value for smbinning should be the column name, not the column.

 results = sapply(paste0("z",1:147), function(foo) { smbinning(df=DATA, y = "FLAG", x = foo, p=0.05) }) class(results) # should be "list" length(results) # should be 147 names(results) # should be z1,... results[[1]] # should be the first result, so you can also iterate by indexing 

I tried the following since you did not provide any data

 > XX=c("IncomeLevel","TOB","RevAccts01") > res = sapply(XX, function(z) smbinning(df=chileancredit.train,y="FlagGB",x=z,p=0.05)) Warning message: NAs introduced by coercion > class(res) [1] "list" > names(res) [1] "IncomeLevel" "TOB" "RevAccts01" > res$TOB ... 

NTN

+5
source share

All Articles