简体   繁体   English

用各种矩阵填充列表,这些矩阵来自矩阵

[英]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. 然后重复此过程10次。 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: 这是我使用的代码,有一天我渴望编写不难看的R代码:

##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. 我不知道你可以用lapply seq_along或seq。 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)),])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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