r - 如何修改文件中的标题?
问题描述
我正在尝试学习在 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 函数可以覆盖先前生成的内容,也可以写入附加到先前写入的文件的底部。通过更改问题代码中的执行顺序,并添加一些新参数,write.table()
我们可以产生所需的结果。
先写标题,然后使用append = TRUE
and column.names = FALSE
in 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
>
推荐阅读
- chef-infra - 刀命令的ChefDk问题
- soap - WSO2 身份服务器密码更改,出现问题“无法访问用户的目录服务”
- php - ajax 请求未加载,因为服务器端 php 文件不可用
- html - HTML 不自动完成或提供选项
- swiftui - SwiftUI – 如何使用列表项点击更改 @State 属性?
- r - 基于条件的列总和
- javascript - 需要将随机生成的数字按数字顺序排序
- android - 如何在 Kotlin 中自定义 Android Studio 的导入顺序以忽略它们是否是“静态”导入?
- sql - 我需要将此查询限制为 1000 条记录并在 TOTAL 字段中显示 count(),我该怎么做?
- perl - 使用 Math::Polygon 确定点是否在多边形内。不工作