How to delimit the number of characters written per line in a "txt" output in R?

Asked

Viewed 103 times

4

I’m writing a filelog and I want to print it on an A4 sheet. One of the parts of this filelog has a variable, with the following structure:

cod<-c(82024,82042,82067,82098,82106,82113,82141,82145,82178,82181,82184,82188,82191,82198,82212,82240,82246,82263,82280,82287,82294,82296,82298,82317,82326,82331,82336,82353,82361,82376,82382,82392,82397,82410,82425,82445,82460,82474,82476,82480,82487,82493,82533,82562,82564,82571,82578,82583,82586,82588,82590,82594,82596,82598,82610,82659,82668,82676,82678,82683)

How can I write the vector cod in a. txt file with up to 80 characters per line, whereas the elements are separated by space as follows::

82487 82493 82533 82562 82564 82571 82578 82586 82588 82590 82594 82596

Each line will have 13 elements (5 characters + 1 space per element).

OBS: The limit of 80 defined as a function of sheet width.

  • 1

    Some questions: What is the point of doing this? How do you want to separate the numbers?

  • I’ll edit the question in a minute!

1 answer

3


What you want can be easily achieved using only the function cat. For example:

cat(cod, file = "jean.txt", fill = 80)

Will create the archive jean.txt with the following content:

82024 82042 82067 82098 82106 82113 82141 82145 82178 82181 82184 82188 82191 
82198 82212 82240 82246 82263 82280 82287 82294 82296 82298 82317 82326 82331 
82336 82353 82361 82376 82382 82392 82397 82410 82425 82445 82460 82474 82476 
82480 82487 82493 82533 82562 82564 82571 82578 82583 82586 82588 82590 82594 
82596 82598 82610 82659 82668 82676 82678 82683

The parameter fill limits the maximum line size, breaking between the elements of cod. If you want to separate the elements with another character, you can use sep. If you want an initial character per line (like when using print), there is the argument labels. You can also test on the console and use file only when you are actually saving. For example:

> cat(cod, fill = 80, labels = paste0("[", seq(1, 1000, by = 12), "]"), sep = ", ")
[1] 82024, 82042, 82067, 82098, 82106, 82113, 82141, 82145, 82178, 82181, 
[13] 82184, 82188, 82191, 82198, 82212, 82240, 82246, 82263, 82280, 82287, 
[25] 82294, 82296, 82298, 82317, 82326, 82331, 82336, 82353, 82361, 82376, 
[37] 82382, 82392, 82397, 82410, 82425, 82445, 82460, 82474, 82476, 82480, 
[49] 82487, 82493, 82533, 82562, 82564, 82571, 82578, 82583, 82586, 82588, 
[61] 82590, 82594, 82596, 82598, 82610, 82659, 82668, 82676, 82678, 82683
  • Thank you! It worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.