繁体   English   中英

在R中另一矩阵的每一行之后插入一个矩阵

[英]Insert one matrix after every row of another matrix in R

我必须准备矩阵,并希望准备某种列表,其中在第一个矩阵的每一行之后重复第二个矩阵。 为了创建矩阵,我使用了库“ plyr”。 这是示例:

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
....

提前谢谢你的帮助。

您可以这样尝试:

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)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM