【问题标题】:Insert one matrix after every row of another matrix in R在R中另一个矩阵的每一行之后插入一个矩阵
【发布时间】:2015-07-28 07:57:08
【问题描述】:

我必须矩阵并且想准备某种列表,其中第二个矩阵在第一个矩阵的每一行之后重复。为了创建矩阵,我使用了库“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
....

提前感谢您的帮助。

【问题讨论】:

    标签: r list matrix


    【解决方案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)
    })
    

    【讨论】:

    • 这看起来很有希望。如何查看生成的文件?还有一些警告“警告消息:1:在 write.table(df, file = blank, append = TRUE, row.names = FALSE, ... : appending column names to file”。这样可以吗?
    • cat(tf) (tf = 临时文件) 查看路径 + 文件名,或在 Windows 上使用shell.exec(tf) 使用与文件扩展名关联的应用程序打开它。您可以忽略警告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多