简体   繁体   中英

Filling a list with a variety of matrices which are samples from a matrix

I'm wanting to fill a list with many different matrices which are created by selecting a variety of different samples from an original matrix. Then repeat this process 10 times. I managed to do it (after much fighting/painful learning process). I would be so grateful if someone could point me in the right direction to get rid of my redundant code and improve the functions I'm using (maybe even get rid of the loops which I gather are rather frowned upon).

My problem hinged on getting the different sized matrices out of the loop.

Here's the code I used, one day I aspire to write R code that is not ugly:

##defining a matrix called allmat
allmat <- matrix(rnorm(100), nrow=50, ncol=2)

##sampling different sizes of the allmat matrix from 0.1*allmat to 10*allmat
for(i in seq(0,9,by=1)) {
  for(j in seq(0.1,10,by=0.05)) {
    nam <- paste("powermatrix_",j,"_",i,sep="")
    assign(nam, allmat[sample(nrow(allmat),replace=T,size=j*nrow(allmat)),])
  }
}

##then using apropos to pick out the names of the matrices from file
##eventually converting matrix list into a list to then use lapply
matrixlist <- data.frame(apropos("powermatrix_"), stringsAsFactors = FALSE)

##then rather horribly trying somehow to get my dataframe into a    
## list which eventually I do below (but although inelegant this bit is 
## not crucial)

colnames(matrixlist) <- "col1"
matrixlist_split <- strsplit(matrixlist$col1, "_")
library("plyr")
df <- ldply(matrixlist_split)
colnames(df) <- c("V1", "V2", "V3")
vector_sample <- as.numeric(df$V2)
mynewdf <- cbind(vector_matrices,vector_sample)

##creating the list before lapply
mylist <- as.list(mget(mynewdf$col1))

##then with the list I can use lapply (but there has to be a much 
## much better way!) 

Many thanks for all your input. This is now working much better with the following two lines. I didn't know you could seq_along or seq with lapply. These two in combination are very helpful.

this vector changes the size and repititions of the matrix sampled

seq_vector    <- c(rep(seq(0.1,1,by=0.1),each=10))

this samples the matrix for all of the sizes and repeats defined by the sequence vector

myotherlist   <- lapply(seq(seq_vector), function(x)   allmat[sample(1:nrow(allmat), replace=T, size=x*nrow(allmat)),])

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