2015-07-28 49 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

相关问题