首页 > 解决方案 > 如何修改文件中的标题?

问题描述

我正在尝试学习在 R 中处理文件的基础知识。我正在尝试更改标题。我尝试writeLines了函数,但它写了一行并删除了文件的其余部分,而不是仅仅修改标题;/你能告诉我我做错了什么吗?这是我的代码

A<-data.frame(X1=c(1,2,3,4), X2=c(5,6,7,8), X3=c(9,10,11,12))
write.table(A, file="file.txt", sep="\t", row.names = FALSE, quote = FALSE) #I create a file.

napis<-paste("Col1","Col2","Col3", sep="\t") #This is going to be the new header.
connection<-file("file.txt", open="w") #I open a connection to write.
writeLines(napis, con=connection) #I'm trying to overwrite a line.
close(connection)

但是当我打开文件时,它只包含新的标题:(

标签: r

解决方案


写入文件的 R 函数可以覆盖先前生成的内容,也可以写入附加到先前写入的文件的底部。通过更改问题代码中的执行顺序,并添加一些新参数,write.table()我们可以产生所需的结果。

先写标题,然后使用append = TRUEand column.names = FALSEin write.table()

A<-data.frame(X1=c(1,2,3,4), X2=c(5,6,7,8), X3=c(9,10,11,12))

napis<-paste("Col1","Col2","Col3", sep="\t") #This is going to be the new header.
connection<-file("file.txt", open="w") #I open a connection to write.
writeLines(napis, con=connection) #I'm trying to overwrite a line.
close(connection)
write.table(A, file="file.txt", sep="\t", row.names = FALSE, col.names = FALSE,
            quote = FALSE,appen = TRUE) #I create a file.

...和输出文件,file.txt如下所示:

Col1    Col2    Col3
1   5   9
2   6   10
3   7   11
4   8   12

为了确认准确性,我们将文件作为数据框读回 R 并打印。

> B <- read.table("file.txt",header = TRUE)
> B
  Col1 Col2 Col3
1    1    5    9
2    2    6   10
3    3    7   11
4    4    8   12
>

推荐阅读