简体   繁体   中英

how to combine the matrices that are output by the for loop in r

I am trying to combine matrices which are output by for loop over all variables inside a function in R? lets say I have 179=length(b) variables, and each variable gives a matrix has 2000 rows=nrow(data.test) and 28 columns=length(x2) . The final matrix should have rows=nrow(data.test) times length(x2) * (ncol(data.test)-1) I tried for loop as follows but the values did not store in the last matrix

  MyFunction <- function(data.train,x2,no.sample,data.test )
{  pre_var  = matrix(,nrow = nrow(data.test), ncol = length(x2) * (ncol(data.test)-1))
for( b in 1:(ncol(data.test)-1))
{  false= NULL ; true=NULL
  pred_test = matrix(,nrow = nrow(data.test), ncol = length(x2))
  for(w in 1:length(x2))
  {  ## there are some lines here to produce false and true values

    pred_test[,w] = as.numeric(ifelse(data.test[,b] > x2[w] 
                                      ,true[w] ,false[w]))}
  pre_var = cbind(pre_var,pred_test)
}
results = NULL
results = pre_var
}

Let's for the sake of simplicity assume that this is a matrix of one of your results

A = matrix(runif(9),ncol=3)

What you want to do, is put them in a list first. In this setting I just repeat my original matrix. In your case you of course generate your matrices

A_list = rep(list(A),5)

The next step is to cbind these together. Here we have a simple cbind-forloop.

n <- length(A_list)
res <- NULL
for(i in seq(n)){
    res <- cbind(res, A_list[[i]])
}
res

Et Voila, I think this is what you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM