[英]Filling a list with a variety of matrices which are samples from a matrix
我想用许多不同的矩阵填充列表,这些矩阵是通过从原始矩阵中选择各种不同的样本而创建的。 然后重复此过程10次。 我设法做到了(经过许多战斗/痛苦的学习过程)。 如果有人能指出正确的方向来消除我的冗余代码并改善我正在使用的功能,我将非常感激(也许甚至摆脱了我收集的循环,对此也很皱眉)。
我的问题在于将不同大小的矩阵移出循环。
这是我使用的代码,有一天我渴望编写不难看的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!)
非常感谢您的所有投入。 现在,以下两行可以更好地工作。 我不知道你可以用lapply seq_along或seq。 两者结合使用非常有帮助。
seq_vector <- c(rep(seq(0.1,1,by=0.1),each=10))
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.