簡體   English   中英

用各種矩陣填充列表,這些矩陣來自矩陣

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM