将data.frame写入R中具有特定格式的文本文件
我正在使用R访问一些旧的FORTRAN输入文件,在将数据帧放入文本文件并保持其格式方面遇到了一些问题 我的方法是:将data.frame写入R中具有特定格式的文本文件,r,R,我正在使用R访问一些旧的FORTRAN输入文件,在将数据帧放入文本文件并保持其格式方面遇到了一些问题 我的方法是: 使用read.table导入数据 调整一列中的数字(乘以标量) 使用write.table函数保存所有内容 我的代码: con <- file(paste(pth,'/Input/met/G_test.MET', sep="")) aaa <- read.table(con) aaa[,2]=aaa[,2]*0.1 write.table(aaa) close(con)
read.table
导入数据write.table
函数保存所有内容con <- file(paste(pth,'/Input/met/G_test.MET', sep=""))
aaa <- read.table(con)
aaa[,2]=aaa[,2]*0.1
write.table(aaa)
close(con)
谢谢你的建议
更新
因为我必须维护格式并更新一列中的数字。我提出了一种“混合”方法。这种方法有效,但我很欣赏关于标准方法的建议
con_rain<- file(paste(pth,'/Out_Test/GA1LEVAP.MET', sep=""))
a_rain=readLines(con_rain)
b_rain=read.table(con_rain)
for (i in 1:731){
a_rain[i]=paste(substr(a_rain[i],1,13),sprintf("%3.2f", b_rain[i,2]*p[19]),substr(a_rain[i],18,37),sep="")
}
writeLines(a_rain, paste(pth,'/Out_Test/GA1LEVAP.MET', sep=""))
con\u rain只需提供一个合适的sep=
参数即可。下面是一个示例,其中包含6个空格,后跟一个选项卡:
R> head(trees)
Girth Height Volume
1 8.3 70 10.3
2 8.6 65 10.3
3 8.8 63 10.2
4 10.5 72 16.4
5 10.7 81 18.8
6 10.8 83 19.7
R> write.table(trees, sep=" \t",
+ file="/tmp/trees6spaces.txt", row.names=FALSE, col.names=FALSE)
R> system("head /tmp/trees6spaces.txt")
8.3 70 10.3
8.6 65 10.3
8.8 63 10.2
10.5 72 16.4
10.7 81 18.8
10.8 83 19.7
11 66 15.6
11 75 18.2
11.1 80 22.6
11.2 75 19.9
R>
我很困惑。您是否期望write.table
的行为与文档中的默认行为不同?@joran:很抱歉造成混淆。我正在尝试为“write.table”函数找到控制输出格式的选项。谢谢您的帮助。还有一个问题,列之间的间距不均匀(前两个是6,最后一个是5)。那么,有没有一种方法可以定义一行的格式并将其应用于表的其余部分呢?
R> head(trees)
Girth Height Volume
1 8.3 70 10.3
2 8.6 65 10.3
3 8.8 63 10.2
4 10.5 72 16.4
5 10.7 81 18.8
6 10.8 83 19.7
R> write.table(trees, sep=" \t",
+ file="/tmp/trees6spaces.txt", row.names=FALSE, col.names=FALSE)
R> system("head /tmp/trees6spaces.txt")
8.3 70 10.3
8.6 65 10.3
8.8 63 10.2
10.5 72 16.4
10.7 81 18.8
10.8 83 19.7
11 66 15.6
11 75 18.2
11.1 80 22.6
11.2 75 19.9
R>