Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 17th, 2012  |  syntax: None  |  size: 1.51 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. R: Format output of write.table
  2. # example data to write to text file
  3.  
  4. aa = matrix(c(1000,110,10,1,
  5.               0,2000,20,2,
  6.               30,300,3000,30000), nrow=3, byrow=TRUE,
  7.          dimnames = list(NULL, c("C1", "C2", "C3","C4")))
  8. aa
  9.  
  10. # left align columns using a tab
  11.  
  12. write.table(aa,file="c:/users/mark w miller/simple r programs/formatted_tablea.txt", na = 'NA', sep = 't',
  13. row.names = F, col.names = F)
  14.  
  15. #   1000    110 10  1
  16. #   0   2000    20  2
  17. #   30  300 3000    30000
  18.  
  19. # increase spacing between columns with two tabs
  20.  
  21. write.table(aa,file="c:/users/mark w miller/simple r programs/formatted_tableb.txt", na = 'NA', sep = 'tt',
  22. row.names = F, col.names = F)
  23.  
  24. #   1000        110     10      1
  25. #   0       2000        20      2
  26. #   30      300     3000        30000
  27.  
  28. # Here is an example of the desired right-aligned output
  29. # format with an intermediate amount of spacing
  30. # (3 spaces vs the 1 or 7 spaces used above):
  31.  
  32. #   1000    110     10       1
  33. #      0   2000     20       2
  34. #     30    300   3000   30000
  35.  
  36. # Maybe use cat somehow?
  37.  
  38. cat(file="c:/users/mark w miller/simple r programs/formatted_tablec.txt", aa, sep=c(' ', ' ', 'n'))
  39.        
  40. capture.output( print(aa, print.gap=3), file="capture.txt")
  41.  
  42.          C1     C2     C3      C4
  43. [1,]   1000    110     10       1
  44. [2,]      0   2000     20       2
  45. [3,]     30    300   3000   30000
  46.        
  47. require(MASS)
  48. write.matrix(aa, file="capturemat.txt", sep="   ")
  49.  
  50. C1   C2   C3   C4
  51.  1000     110      10       1
  52.     0    2000      20       2
  53.    30     300    3000   30000