2015-07-28 47 views
1

我必須制定矩陣並且希望準備某種列表,其中在第一矩陣的每一行之後重複第二矩陣。爲了創建矩陣,我使用了庫「plyr」。這裏是例子:在R中的另一個矩陣的每一行之後插入一個矩陣

library(plyr) 
# first matrix 
a <- c(1,2) 
b <- c(1,2) 
c <- c(1,2,3) 
mat1 <- expand.grid(a= a, b= b, c= c) 
mat1 <- mat1[order(mat1$a, mat1$b), ] 
mat1 

# second matrix 
mat2 = matrix(data= c(rep(0, 9)), nrow= 3, ncol= 3) 
mat2 

因此產生的txt文件看起來像這樣

a=1 b=1 c=1 
0 0 0 
0 0 0 
0 0 0 
a=1 b=1 c=2 
0 0 0 
0 0 0 
0 0 0 
a=1 b=1 c=3 
.... 

感謝您對您的幫助提前。

回答

1

你可以嘗試這樣的:

tf <- tempfile(fileext = ".csv") 
apply(mat1, 1, function(x) { 
    df <- setNames(data.frame(mat2, check.names = FALSE), paste(names(mat1), x, sep = "=")) 
    write.table(df, file = tf, append = TRUE, row.names = FALSE, quote = FALSE) 
}) 
+0

這看起來很有希望。我怎樣才能看到生成的文件?還有一些警告:「警告消息:1:在write.table(df,file = blank,append = TRUE,row.names = FALSE,...:將列名附加到文件中)。這是行嗎? – Eco06

+1

'cat (tf)'(tf =臨時文件)在Windows上查看路徑+文件名或'shell.exec(tf)'以使用與文件擴展名關聯的應用程序打開它。您可以忽略該警告。 – lukeA

+0

謝謝你快速重播 – Eco06

相關問題