write.table列不与空格

时间:2016-01-26 19:07:30

标签: r write.table

我有一个大部分空白的数据框,可以使用下面的输入读取:

structure(list(var1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), var2 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), var3 = c(NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA), var4 = c(NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA), var5 = c(NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA), var6 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), 
    var7 = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), var8 = c(NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA), var9 = c(NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA), var10 = c(NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA)), .Names = c("var1", "var2", "var3", 
"var4", "var5", "var6", "var7", "var8", "var9", "var10"), row.names = c(NA, 
10L), class = "data.frame")

我想把它写成TXT文件,看起来所有内容都格式正确并且可以在Excel中轻松打开(我知道write.xlsx虽然它解决了这个问题但我希望文件在txt格式)。

write.table(df3, file="test.txt", quote = FALSE, na = " \t", row.names = FALSE)

我尝试了这个但是值没有正确对齐:例如,应该在var7下的值显示在var6 intead上。此外,虽然Excel设法将列读取为独立的,但包含变量名称的标题行将被读取为一个长向量。是什么给了什么?

2 个答案:

答案 0 :(得分:1)

使用write.table(df3, file="test.txt", quote = FALSE, sep = "\t", na="", row.names = FALSE)请注意,sep = "\t"代替na = " \t"并设置na=""

答案 1 :(得分:0)

如果我写:

write.table(df3, file="test.txt", quote = FALSE, sep="\t", row.names = FALSE, na="")

然后它有效。我遵循了Jilber关于使用sep="\t"的建议,并对na选项执行了此操作,否则NAs将显示在文件中。