【问题标题】:R write.table does not write 2 matrices on the same fileR write.table 不在同一个文件上写入 2 个矩阵
【发布时间】:2016-07-28 05:10:39
【问题描述】:

我有 2 个矩阵 x 和 y。我想按以下顺序将它们写在同一个 csv 文件中:矩阵 x、“一些文本”、矩阵 y。我使用函数 write.table 来附加文件。但是,只有 y 矩阵被写入而 x 矩阵丢失。我注意到,如果我在 2 个命令 write.table 中删除“一些文本”,两个矩阵都会正确打印出来。实际上,我想在打印矩阵 y 之前保留“一些文本”,因为这将帮助我识别我在大数据测试中的结果。你有什么建议吗?谢谢。

rm(list=ls())
cat("\014")

file_ext="csv"
output_file = paste("result", file_ext, sep = ".")

(x <- matrix(1, nrow = 3, ncol = 2, byrow = TRUE))
(y <- matrix(2, nrow = 3, ncol = 2, byrow = TRUE))

sink(output_file)
#------------------------------------------------------------
cat("The results are:",sep="\n")

#write the x matrix. PROBLEM: the x matrix is not printed out
cat("The x matrix",append =TRUE)
cat("\n")
write.table(x, file=output_file, sep=",", col.names = F, row.names = F, append = TRUE)

#write the y matrix. 
cat("The y matrix",append =TRUE)
cat("\n")
write.table(y, file=output_file, sep=",", col.names = F, row.names = F, append = TRUE)

sink()
file.show(output_file) #show the file in directory

【问题讨论】:

    标签: r


    【解决方案1】:

    这是你想要的吗?

    The results are:    
    The x matrix    
    1   1
    1   1
    1   1
    The y matrix    
    2   2
    2   2
    2   2
    

    代码:

    rm(list=ls())
    
    file_ext="csv"
    output_file = paste("result", file_ext, sep = ".")
    
    (x <- matrix(1, nrow = 3, ncol = 2, byrow = TRUE))
    (y <- matrix(2, nrow = 3, ncol = 2, byrow = TRUE))
    
    sink(output_file)
    
    cat("The results are:\nThe x matrix\n")
    write.table(x,row.names=FALSE,col.names=FALSE,sep=",")
    
    cat("The y matrix\n")
    write.table(y,row.names=FALSE,col.names=FALSE,sep=",")
    
    sink()
    file.show(output_file) #show the file in directory
    

    【讨论】:

    • 是的,这是我的预期结果。您的修复工作完美。非常感谢。
    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    相关资源
    最近更新 更多