代码之家  ›  专栏  ›  技术社区  ›  Yannick Wurm

当有行名时,write.table将不需要的前导空列写入标头

  •  76
  • Yannick Wurm  · 技术社区  · 16 年前

    > a = matrix(1:9, nrow = 3, ncol = 3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
    > a
      A B C
    A 1 4 7
    B 2 5 8
    C 3 6 9
    

    表格显示正确。有两种不同的方式写入文件。。。

    write.csv(a, 'a.csv') 如预期:

    "","A","B","C"
    "A",1,4,7
    "B",2,5,8
    "C",3,6,9
    

    write.table(a, 'a.txt') 哪个搞砸了

    "A" "B" "C"
    "A" 1 4 7
    "B" 2 5 8
    "C" 3 6 9
    

    这是一个bug还是一个特性? 有解决办法吗(除 write.table(cbind(rownames(a), a), 'a.txt', row.names=FALSE

    扬尼克

    5 回复  |  直到 10 年前
        1
  •  145
  •   Marek    10 年前

    ?write.table ,节 :

    默认情况下,没有列名称 行名称列。如果 col.names = NA 和 row.names = TRUE 一片空白 添加列名,即 用于CSV文件的约定

    所以你必须这么做

    write.table(a, 'a.txt', col.names=NA)
    

    "" "A" "B" "C"
    "A" 1 4 7
    "B" 2 5 8
    "C" 3 6 9
    
        2
  •  10
  •   rusalkaguy    10 年前

    > a = matrix(1:9, nrow = 3, ncol = 3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
    > write.table(data.frame("H"=rownames(a),a),"a.txt", row.names=FALSE)
    

    然后你得到

    "H" "A" "B" "C"
    "A" 1 4 7
    "B" 2 5 8
    "C" 3 6 9
    
        3
  •  4
  •   Keith Hughitt rjhcnf    9 年前

    tidyverse (dplyr等),the rownames_to_column() 从 tibble

    library('tibble')
    a = as.data.frame(matrix(1:9, nrow=3, ncol=3, 
                      dimnames=list(LETTERS[1:3], LETTERS[1:3])))
    
    a %>% rownames_to_column('my_id')
    
      my_id A B C
    1     A 1 4 7
    2     B 2 5 8
    3     C 3 6 9
    

    把这个和 row.names=FALSE 中的选项 write.table() 结果是所有列都有标题名的输出。

        4
  •  2
  •   LeCodex    8 年前

    对于在保存矩阵时遇到相同问题的用户 write.table() 要保留row.names列,实际上有一个非常简单的解决方案:

     write.table(matrix,file="file.csv",quote=F,sep=";", row.names=T
                 col.names=c("row_name_col;val1_col","val2_col"))
    

    write.table 函数为row.names列创建标题标签。生成的.csv文件如下所示:

    row_name_col;val1_col;val2_col
    row1;1;4 
    row2;2;5 
    row3;3;6 
    
        5
  •  0
  •   yuanhangliu1    11 年前

    我修改了@mnel中的一个简单函数,它通过使用连接增加了灵活性。函数如下:

    my.write <- function(x, file, header, f = write.csv, ...){
    # create and open the file connection
    datafile <- file(file, open = 'wt')
    # close on exit 
    on.exit(close(datafile))
    # if a header is defined, write it to the file (@CarlWitthoft's suggestion)
    if(!missing(header)) {
    writeLines(header,con=datafile, sep='\t')
    writeLines('', con=datafile, sep='\n')
    }
    # write the file using the defined function and required addition arguments  
    f(x, datafile,...)
    }
    

    干杯!