【问题标题】:R read.table <-> write.tableR read.table <-> write.table
【发布时间】:2012-02-20 14:52:03
【问题描述】:

在 R 中:

d=read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = 1)

从 d 写回完全相同的文件的命令是什么?

write.table(d, ?)

我给你一个示例输入文件:

one two
1   2

分隔符是“\t”。用 read.table 读取后会写入完全相同的输出文件的 write.table 参数是什么?

谢谢你, 格雷戈尔

【问题讨论】:

    标签: r


    【解决方案1】:
    write.table(d,"filename")
    

    您必须指定要使用的文件扩展名。希望它有效。

    【讨论】:

    • Tnx,但 unf。不会产生与输入文件相同的输出文件。
    • @rgregor 您是否在write.table 中指定了sep = "\t" 参数?您需要查看 write.table 的所有参数并为每个参数选择正确的值,以指定您感兴趣的确切文件格式。
    • joran:谢谢,我完善了我的问题。现在应该更清楚了。我找不到 write.table 的正确参数,你可以吗?
    • 我确实阅读了它,但仍然找不到正确的参数。你能和我们分享一下吗?
    • @rgregor,你明白了吗?如果没有,你能放一个你的数据实例吗?
    【解决方案2】:

    问题是您的read.table 将第 1 列用作row.names,因此它丢失了列名(“one”)。当你把它写出来时,你必须做一些特别的事情来恢复“一”的名字。

    cbind(one=row.names(d), d) 会将 row.names 添加为名称为“one”的列。然后你只需要禁用 row.names 和引号,并指定分隔符:

    # Create the test file
    filename <- "test.txt"
    filename2 <- "test2.txt"
    cat("one\ttwo\n1\t2\n", file=filename)
    
    # read it in
    d <- read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = 1)
    
    # write it out again
    write.table(cbind(one=row.names(d), d), filename2, row.names=FALSE, sep="\t", quote=FALSE)
    
    # Ensure they are the same:
    identical(readLines(filename), readLines(filename2)) # TRUE
    
    readLines(filename)
    readLines(filename2)
    

    更新为避免对第一列名称进行硬编码,加载时不能丢失它:

    # Read the data without any row.names
    d <- read.table(filename, as.is = TRUE, header = TRUE, sep = "\t", row.names = NULL)
    # Then use the first column as row.names (but keeping the first column!)
    row.names(d) <- d[[1]]
    d
    #  one two
    #1   1   2        
    
    # Now you can simply write it out...
    write.table(d, filename2, row.names=FALSE, sep="\t", quote=FALSE)
    
    # Ensure they are the same:
    identical(readLines(filename), readLines(filename2)) # TRUE
    

    如果您保留它的名称并像第一个示例一样使用它,您当然仍然可以删除第 1 列。

    【讨论】:

    • Tnx 但我不想在我的代码中硬编码列的名称(one=row.names(d) 部分)。这并不意味着它是通用的。还有其他想法吗?
    • 那你必须以不同的方式阅读它!我会更新答案。
    • Tnx:另外,我仍然想像以前一样设置 d 的行名(从第 1 列读取)。
    • 太棒了!这真的很有帮助,非常有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多