【问题标题】:R: Format output of write.tableR:write.table的格式输出
【发布时间】:2012-06-22 20:51:08
【问题描述】:

是否可以用 write.table 格式化输出?

我可以使用制表符 sep = '\t' 使列左对齐,并且可以使用两个制表符 sep = '\t\t' 增加列之间的间距。

理想情况下,我希望能够右对齐列并使用比提供的中间量的间距 通过'\t'和'\t\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 创建所需格式的输出数据?

抱歉这周的所有问题。

【问题讨论】:

  • 您能否解释一下校对数据的概念以及涉及的操作类型。根据打样的性质,我可能会考虑另一种解决方案。

标签: r


【解决方案1】:

看看capture.outputprint的print.gap参数的组合是否足够:

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

【讨论】:

  • capture.output 是否有对应的 row.names = FALSE?好像没有
  • 不适用于 capture.output,但您应该尝试在 print 调用中使用它。
【解决方案2】:
gdata 库中的

write.fwf 函数对此非常有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2017-03-25
    • 2015-04-22
    • 2018-04-17
    • 2011-12-06
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多