loops - Creating multiplicative interaction variables using R -


i trying write function calculates multiplicative interactions of variables specify. refer code below idea of trying do.

mul <- function(data, vars) { for(ii in vars)  {   for(jj in vars[ii : length(vars)])   {    data[, paste(ii, jj, sep = "mul")] <-     data[,  which(colnames(data) %in%   ii)]*data[,   which(colnames(data) %in% jj)]   }   } test    } 

since amateur in r, r black belt coders me out here.

as data example, want below code work in end:

data(iris) x <- names(iris)[1:4] mul(iris, x)  

and gives me 4c2 (6) additional variables in iris data.frame multiplicative variables. finally, need data frame 70k obs , ~100 variables. in advance!

avoid loops altogether, use combn:

data(iris) x <- names(iris)[1:4] combn(x,2,fun=function(x) iris[,x[1]] * iris[,x[2]]  ) #      [,1]  [,2]  [,3]  [,4] [,5]  [,6] #[1,] 17.85  7.14  1.02  4.90 0.70  0.28 #[2,] 14.70  6.86  0.98  4.20 0.60  0.28 #[3,] 15.04  6.11  0.94  4.16 0.64  0.26 #[4,] 14.26  6.90  0.92  4.65 0.62  0.30 # etc etc 

if want set names @ same time, do:

iris[combn(x,2,fun=paste0,collapse=".by.")] <-    combn(x,2,fun=function(x) iris[,x[1]] * iris[,x[2]] ) 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -