[英]R: Format output of write.table
是否可以使用write.table格式化输出?
我可以使用tab, sep = '\\t'
来左对齐列,并且可以使用两个选项卡sep = '\\t\\t'
来增加列之间的间距。
理想情况下,我希望能够右对齐列并使用中间数量的间距,而不是'\\ t'和'\\ t \\ t'提供的间距。 使用sep = '\\t '
类的东西sep = '\\t '
完全破坏列对齐。
我必须证明从使用多种不同表格格式的许多不同文件中提取的大量数据。 将R的输出文本文件的列间距与原始pdf文档中的列间距紧密匹配将大大提高校对的速度和准确性。
# example data to write to text file
aa = matrix(c(1000,110,10,1,
0,2000,20,2,
30,300,3000,30000), nrow=3, byrow=TRUE,
dimnames = list(NULL, c("C1", "C2", "C3","C4")))
aa
# left align columns using a tab
write.table(aa,file="c:/users/mark w miller/simple r programs/formatted_tablea.txt", na = 'NA', sep = '\t',
row.names = F, col.names = F)
# 1000 110 10 1
# 0 2000 20 2
# 30 300 3000 30000
# increase spacing between columns with two tabs
write.table(aa,file="c:/users/mark w miller/simple r programs/formatted_tableb.txt", na = 'NA', sep = '\t\t',
row.names = F, col.names = F)
# 1000 110 10 1
# 0 2000 20 2
# 30 300 3000 30000
# Here is an example of the desired right-aligned output
# format with an intermediate amount of spacing
# (3 spaces vs the 1 or 7 spaces used above):
# 1000 110 10 1
# 0 2000 20 2
# 30 300 3000 30000
# Maybe use cat somehow?
cat(file="c:/users/mark w miller/simple r programs/formatted_tablec.txt", aa, sep=c(' ', ' ', '\n'))
或者我必须写入csv文件并用Excel打开输出文件? 我宁愿避免使用Excel。 或许我必须使用LaTex以所需的格式创建输出数据?
对不起本周的所有问题。
看看的组合capture.output
和print.gap参数print
就够了:
capture.output( print(aa, print.gap=3), file="capture.txt")
C1 C2 C3 C4
[1,] 1000 110 10 1
[2,] 0 2000 20 2
[3,] 30 300 3000 30000
另一种策略是使用带有sep=" "
(3个空格)参数的write.matrix。 您将需要忽略不正确的列标题:
require(MASS)
write.matrix(aa, file="capturemat.txt", sep=" ")
C1 C2 C3 C4
1000 110 10 1
0 2000 20 2
30 300 3000 30000
来自gdata库的write.fwf
函数对此非常write.fwf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.