6

write.table で出力をフォーマットすることは可能ですか?

タブをsep = '\t'使用して列を左揃えにし、2 つのタブを使用して列間の間隔を広げることができます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 で開く必要がありますか? エクセルはやめたほうがいいです。それとも、LaTex を使用して目的の形式で出力データを作成する必要がありますか?

今週は質問ばかりですみません。

4

2 に答える 2

8

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
于 2012-06-22T21:01:57.317 に答える