[英]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.