简体   繁体   中英

R: Format output of write.table

Is it possible to format output with write.table?

I can left-align columns using tab, sep = '\\t' , and can increase spacing between columns using two tabs, sep = '\\t\\t' .

Ideally I would like to be able to right-align columns and use an intermediate amount of spacing than that provided by '\\t' and '\\t\\t'. Using something like sep = '\\t ' completely destroyes column alignment.

I must proof a large amount of data extracted from many different files that use numerous different table formats. Closely matching column spacing of R's output text files to that in the original pdf documents would substantially increase speed and accuracy of proofing.

# 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'))

Or must I write to a csv file and open the output file with Excel? I would prefer to avoid Excel. Or perhaps I must create the output data in the desired format using LaTex?

Sorry for all of the questions this week.

See if the combination of capture.output and the print.gap argument to print is enough:

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

An alternate strategy would be to use write.matrix with a sep=" " (3 spaces) argument. You will need to ignore the column headers which will not come out correctly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM