cat(…, file=”", sep=” “, append=FALSE)
Print output to the screen or to a file. Use cat to print information to an end-user from a function. cat is also useful for writing information that is being processed or generated, one or more lines at a time, to a file.
- … – The information to be printed to the screen or saved to a file.
- file – An optional argument that specifies a file to be created, overwritten, or appended.
- sep – Specifies what separates the objects in … that are to be printed.
- append – If a file is specified, then indicate whether to append to the content in the existing file (the default is not to append, which means to overwrite the existing content).
Example. Below are several simple examples of using cat, followed by examples leading up to writing information into a file. To use a tab separator, use "\t", and use "\n" to create a line break.
> set.seed(5) > N <- 12 > x <- rpois(N, rpois(N, 1.5)) > x [1] 0 1 3 0 0 1 1 4 4 0 2 2 > > # Space separator > cat(x) 0 1 3 0 0 1 1 4 4 0 2 2 > > # Multi-space separator > cat(x, sep=" . ") 0 . 1 . 3 . 0 . 0 . 1 . 1 . 4 . 4 . 0 . 2 . 2 > > # Tab separator > cat(x, sep="\t") 0 1 3 0 0 1 1 4 4 0 2 2 > > # Line Break separator > cat(x, sep="\n") 0 1 3 0 0 1 1 4 4 0 2 2 > > y <- sample(c("home", "away"), N, TRUE) > y [1] "away" "home" "home" "home" "home" "home" "away" [8] "home" "away" "home" "home" "home" > > cat(x, y) 0 1 3 0 0 1 1 4 4 0 2 2 away home home home home home away home away home home home > > cat(x[1], y[1], sep="\t") 0 away > > #===> Practice Run For Writing File <===# > for(i in 1:3){ + cat(x[i], y[i], sep="\t") + cat("\n") + } 0 away 1 home 3 home > > #===> Could Append To Existing File <===# > for(i in 1:N){ + cat(x[i], y[i], file="data1.txt", sep="\t", append=TRUE) + cat("\n", file="data1.txt", append=TRUE) + }
No comments:
Post a Comment