2017-06-19 76 views
0

我是R新手,目前正在學習創建for循環。在一個循環中創建多個矩陣

我想要做的就是創建6點矩陣具有相似的結構是這樣的(唯一的區別是該行「A」與基體的數量而變化):

matrix1<- matrix(nrow=5, ncol=5, dimnames= list(c("a", "b", "c", "d", "e") 

for(i in 1:5){ 
matrix1[1,]= 1 
matrix1[2,]= round(rpois(5,1), digits=0) 
matrix1[3,]= round(rpois(5,1), digits= 0) 
matrix1[4,]= round(rnorm(5, 50, 25), digits= 0) 
matrix1[5,]= round(rnorm(5, 50, 25), digits= 0) 
} 

有沒有什麼有效的方法使用循環,而不是單獨做這個?

我還考慮創建填充NA值的6個5 * 5矩陣,然後用這些值填充所需的值,但我不知道該怎麼做。

如果你能幫助我,這將是非常好的! 謝謝!

+3

寫'x'的功能,使矩陣,然後執行'lapply(values_for_x,有趣)'?請注意,最好有一個矩陣列表,而不是像matrix1,matrix2,... – Frank

+0

這樣的名稱中嵌入矩陣數字,但是如何編寫此函數?你能舉個例子嗎? –

+0

'fun < - function(x){your_code_here_over_multiple_lines}'在花括號裏面,你可以像上面那樣編寫你的代碼,確保它使用函數參數('x'或者你想要調用它的任何東西)一行「因你想要的而不同。 – Frank

回答

0

for循環不需要,你的代碼在沒有它的情況下運行。在R中,for循環允許你創建一個臨時對象,在每個循環中循環1次到5次(在你的情況下)。爲了利用循環,您需要使用i。你當前的for循環實際上只覆蓋了5次。

這是一個循環,在列表中創建6個矩陣。這裏的技巧是,我使用i不僅在列表中創建一個新元素(矩陣),而且還將第一行設置爲隨數字矩陣變化。

# First it is good to initialize an object that you will iterate over 
lists <- vector("list", 6) # initialize to save time 

for(i in 1:6){ 
    # create a new matrix and set all values in it to be i 
    lists[[i]] <- matrix(i, nrow = 5, ncol = 5, dimnames= list(c("a", "b", "c", "d", "e") 
)) 
    # change the remaining rows 
    lists[[i]]["b",] <- round(rpois(5,1), digits = 0) 
    lists[[i]]["c",] <- round(rpois(5,1), digits = 0) 
    lists[[i]]["d",] <- round(rnorm(5, 50, 25), digits= 0) 
    lists[[i]]["e",] <- round(rnorm(5, 50, 25), digits= 0) 
} 

# Properly name your lists 
names(lists) <- paste0("Matrix",1:6) 

# Now you can call the lists individually with 
lists$Matrix1 

# Or send them all to your environment with 
list2env(lists, env = .GlobalEnv) 

讓我知道如果這能幫助或者如果您有任何問題〜