fstevens
fstevens

Reputation: 1297

Add % symbol to data in a table in r

I would like to save a table as a figure (using "tableGrob" from gridExtra package). This works without any problem.

But before doing that, I need to add the "%" symbol at all the values in the table. However, pasting the symbol to the table transforms the table into a vector.

my.table <- table(diamonds$cut, diamonds$color)

str(my.table)
'table' int [1:5, 1:7] 163 662 1513 1603 2834 224 933 2400 2337 3903 ...
- attr(*, "dimnames")=List of 2
..$ : chr [1:5] "Fair" "Good" "Very Good" "Premium" ...
..$ : chr [1:7] "D" "E" "F" "G" ...

my.table <- format(100*my.table, 2)

          D        E        F        G        H        I        J      
Fair      "16300"  "22400"  "31200"  "31400"  "30300"  "17500"  "11900"
Good      "66200"  "93300"  "90900"  "87100"  "70200"  "52200"  "30700"
Very Good "151300" "240000" "216400" "229900" "182400" "120400" "67800"
Premium   "160300" "233700" "233100" "292400" "236000" "142800" "80800"
Ideal     "283400" "390300" "382600" "488400" "311500" "209300" "89600"

Still ok , but the next command destroys the table :

my.table <- paste(my.table, '%')
str(my.table)
"character"

Would you know a way to circumvent this?

Upvotes: 0

Views: 1525

Answers (3)

MvG
MvG

Reputation: 60968

You can copy the attributes to restore the table form:

my.table2 <- paste(my.table, '%')
attributes(my.table2) <- attributes(my.table)
my.table <- my.table2

If you want to avoid the extra name, the following code does that, although it is harder to read:

my.table <- `attributes<-`(paste(my.table, '%'), attributes(my.table))

Upvotes: 0

Ernest A
Ernest A

Reputation: 7839

Another way:

replace(my.table, TRUE, sprintf('%d%%', my.table))

I agree with @joran that R is not intended for typesetting nice tables.

Upvotes: 2

joran
joran

Reputation: 173657

One thing you could do is simply rebuild the table:

m <- paste(my.table, '%')
matrix(m,5,7,dimnames = dimnames(my.table))

But if, as seems likely, this table is headed towards being output in LaTeX (or something similar) it might make more sense to add the % symbol when converting it to whatever markup language you're using, rather then within the data structure in R.

Upvotes: 2

Related Questions