cat
Concatenate and Print
Outputs the objects, concatenating the representations. cat
performs much less conversion than print
.
- Keywords
- file, print, connection
Usage
cat(… , file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE)
Arguments
- …
R objects (see ‘Details’ for the types of objects allowed).
- file
A connection, or a character string naming the file to print to. If
""
(the default),cat
prints to the standard output connection, the console unless redirected bysink
. If it is"|cmd"
, the output is piped to the command given bycmd
, by opening a pipe connection.- sep
a character vector of strings to append after each element.
- fill
a logical or (positive) numeric controlling how the output is broken into successive lines. If
FALSE
(default), only newlines created explicitly by "\n" are printed. Otherwise, the output is broken into lines with print width equal to the optionwidth
iffill
isTRUE
, or the value offill
if this is numeric. Non-positivefill
values are ignored, with a warning.- labels
character vector of labels for the lines printed. Ignored if
fill
isFALSE
.- append
logical. Only used if the argument
file
is the name of file (and not a connection or"|cmd"
). IfTRUE
output will be appended tofile
; otherwise, it will overwrite the contents offile
.
Details
cat
is useful for producing output in user-defined functions.
It converts its arguments to character vectors, concatenates
them to a single character vector, appends the given sep =
string(s) to each element and then outputs them.
No linefeeds are output unless explicitly requested by "\n"
or if generated by filling (if argument fill
is TRUE
or
numeric).
If file
is a connection and open for writing it is written from
its current position. If it is not open, it is opened for the
duration of the call in "wt"
mode and then closed again.
Currently only atomic vectors and names are handled,
together with NULL
and other zero-length objects (which produce
no output). Character strings are output ‘as is’ (unlike
print.default
which escapes non-printable characters and
backslash --- use encodeString
if you want to output
encoded strings using cat
). Other types of R object should be
converted (e.g., by as.character
or format
)
before being passed to cat
. That includes factors, which are
output as integer vectors.
cat
converts numeric/complex elements in the same way as
print
(and not in the same way as as.character
which is used by the S equivalent), so options
"digits"
and "scipen"
are relevant. However, it uses
the minimum field width necessary for each element, rather than the
same field width for all elements.
Value
None (invisible NULL
).
Note
If any element of sep
contains a newline character, it is
treated as a vector of terminators rather than separators, an element
being output after every vector element and a newline after the
last. Entries are recycled as needed.
References
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
See Also
Examples
library(base)
# NOT RUN {
iter <- stats::rpois(1, lambda = 10)
## print an informative message
cat("iteration = ", iter <- iter + 1, "\n")
## 'fill' and label lines:
cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
# }
Community examples
 ## Basic usage `cat()` prints output to the console. ```r cat("Miaow!") ``` If you pass it an atomic vector, it prints the each element of the input separated by spaces. For comparison, look at how [`paste()`](https://www.rdocumentation.org/packages/base/topics/paste) behaves with the same input. ```r cat(LETTERS) paste(LETTERS) ``` `cat()` returns `NULL`; it exists purely for the side-effect of writing output, not for creating new variables. ```r x <- cat(1:10) is.null(x) ``` If you pass multiple atomic vectors to `cat()`, the vectors are written one after the other. Again, compare the behavior to [`paste()`](https://www.rdocumentation.org/packages/base/topics/paste). ```r cat(LETTERS, letters) paste(LETTERS, letters) ``` `cat()` can be thought of as a low-level version of [`print()`](https://www.rdocumentation.org/packages/base/topics/print). In the following example, notice how `cat()` and `print()` behave differently with the tab (`\t`) and newline (`\n`) characters. ```r x <- "a b\tc\nd" print(x) cat(x) ``` The names of the input vectors are ignored. ```r cat(setNames(letters, LETTERS)) ``` ## Passing `matrix`, `list`, and other object types If you pass a `matrix` to `cat()`, it will ignore the dimensions and pretend that you passed a vector. ```r cat(matrix(month.abb, 3)) ``` If you pass a `list` to `cat()`, it will throw an error. You may wish to use [`do.call()`](https://www.rdocumentation.org/packages/base/topics/do.call), or change the input type to `cat()` using [`purrr::lift_dl()`](https://www.rdocumentation.org/packages/purrr/topics/lift). ```r tryCatch( cat(list(1, 2, 3)), error = print ) do.call(cat, list(1, 2, 3)) purrr::lift_dl(cat)(list(1, 2, 3)) ``` `cat()` will drop attributes of its inputs. This is particularly tricksy when it comes to `factor`s and `Date`s. Convert them to `character` before calling `cat()`. ```r cat(Sys.Date()) cat(as.character(Sys.Date())) cat(factor(letters)) cat(as.character(factor(letters))) ``` ## `file` argument As well as writing output to the console, `cat()` can write to a file by passing a string to the `file` argument. ```r tmp <- tempfile() cat(1:10, file = tmp) readLines(tmp) ``` `cat()` also supports writing to file [`connection()`](https://www.rdocumentation.org/packages/base/topics/connections)s. ```r tmp <- tempfile() conn <- file(tmp, "w") cat(1:10, file = conn) close(conn) readLines(tmp) ``` ## `sep` argument The spacing between elements of the vectors can be controlled with the `sep` argument. ```r cat(letters, sep = "***") ``` `sep` is vectorized. ```r cat(letters, sep = LETTERS) ``` ## `fill` argument If `fill` is a positive integer then the output is wrapped with a newline (`\n`) after `fill` characters. See [`strwrap()`](https://www.rdocumentation.org/packages/base/topics/strwrap) for comparison. ```r cat(letters, fill = 10) strwrap( paste(letters, collapse = " "), width = 10 ) ``` `fill = TRUE` is a short way of writing `fill = getOption("width")`. See [`options()`](https://www.rdocumentation.org/packages/base/topics/options) for details of the global options, and [`withr::with_option()`](https://www.rdocumentation.org/packages/withr/topics/with-option) for a way to temporarily change global options. ```r withr::with_options( c(width = 20), cat(letters, fill = TRUE) ) ``` ## `append` argument When writing a file, by default `cat()` will overwrite the existing contents of the file. ```r tmp <- tempfile() cat(1:10, file = tmp) cat(11:20, file = tmp) readLines(tmp) # only the 2nd line is present in the file ``` Set `append = TRUE` in all calls to `cat()` after the first to fix this problem. ```r tmp <- tempfile() cat(1:10, file = tmp) cat(11:20, file = tmp, append = TRUE) readLines(tmp) # both lines are present in the file ``` ## Writing `print()` functions [`print()`](https://www.rdocumentation.org/packages/base/topics/print) is a generic function that controls how objects are displayed in the console. Most `print()` methods include calls to `cat()` to create that output. ```r print.Date stats:::print.lm ```