[R] Problem with cat() == A related question
William Dunlap
wdunlap at tibco.com
Thu Sep 16 18:04:51 CEST 2010
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Peng, C
> Sent: Thursday, September 16, 2010 5:39 AM
> To: r-help at r-project.org
> Subject: Re: [R] Problem with cat() == A related question
>
>
> The question is wehter cat() can print out a matrix as it is.
> For example,
> Let's assume that we have matrices A, B, D(= A+B), if it is
> possible that
> cat("\n", A, "+",B,"=", D, < some control arguments >, "\n")
> prints out
>
> matrix A + matrix B = matrix D
>
> where matrices A, B, D (= A+B) should be in the form of their actual
> matrices.
cat() will not do that. I use a function, SideBySide(x,y)
to print two objects next to each other. It does it by
capturing the printed output of each as character vectors,
then cbinding them together into a 2 column character matrix
which the standard print routine will print nicely.
Typical usage is
> A<-matrix(1:12,nrow=3)
> B<-matrix(100,nrow=3,ncol=4)
> sideBySide(A,A+B)
A A + B
[,1] [,2] [,3] [,4] [,1] [,2] [,3] [,4]
[1,] 1 4 7 10 [1,] 101 104 107 110
[2,] 2 5 8 11 [2,] 102 105 108 111
[3,] 3 6 9 12 [3,] 103 106 109 112
Perhaps you can adapt it to your needs by letting it
take more than two arguments and adding some separators.
sideBySide <- function (a, b, argNames) {
oldWidth <- options(width = getOption("width")/2 - 4)
on.exit(options(oldWidth))
if (missing(argNames)) {
argNames <- c(deparse(substitute(a))[1],
deparse(substitute(b))[1])
}
pa <- capture.output(print(a))
pb <- capture.output(print(b))
nlines <- max(length(pa), length(pb))
length(pa) <- nlines
length(pb) <- nlines
pb[is.na(pb)] <- ""
pa[is.na(pa)] <- ""
retval <- cbind(pa, pb, deparse.level = 0)
dimnames(retval) <- list(rep("", nrow(retval)), argNames)
noquote(retval)
}
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> --
> View this message in context:
> http://r.789695.n4.nabble.com/Problem-with-cat-tp2538811p2542098.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list