[R] cat, and printing the last separator

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jan 25 12:54:11 CET 2012


On 12-01-25 6:35 AM, Federico Calboli wrote:
> Hi All,
>
> I have the following command:
>
> cat(rbind(table(gen$sex, gen$ddn2)[1,],round(table(gen$sex, gen$ddn2)[1,]/apply(table(gen$sex, gen$ddn2),2,sum) * 100)), sep = c(' (','%)\n'), file = '')
>
> 3 (20%)
> 17 (30%)
> 15 (31
>
> i.e. it does NOT print the last separator, which is something that bugs me a bit, given that fact I'm trying to have some copy-paste ready stuff to put in a table.

I think the documentation for cat is a little ambiguous, but it is 
working as documented if I read "If any element of sep contains a 
newline character," to mean that the element consists of a newline and 
nothing else.  I'm not sure if that was the intended reading or not.

>
> How would I overcome this issue? I tried a number of things, all of which have failed.
>

I'd use sprintf for that, i.e. something like

count <- c(3, 17, 15)
pct <- c(20, 30, 31)
cat(sprintf("%d (%d%%)\n", count, pct), sep="")

where count and pct are the vectors of values to go into the display.

Duncan Murdoch



More information about the R-help mailing list