2012-11-16 23 views
0

我想將表格保存爲圖形(使用gridExtra包中的「tableGrob」)。這工作沒有任何問題。將%符號添加到r表中的數據

但在此之前,我需要在表格中的所有值上添加「%」符號。但是,將符號粘貼到表格會將表格轉換爲矢量。

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" 

還OK,但下一個命令破壞表:

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

你會知道的方式來規避呢?

回答

2

有一兩件事你可以做的是簡單地重建表:

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

但是,如果像很可能,這個表是邁向在乳膠(或類似的東西)輸出,就把它可能會更有意義添加在%符號將其轉換爲任何標記語言,你使用,而不是數據結構內R.

+0

事實上,將表格導出到LaTeX「\%」時是必要的。但我只知道「xtable」函數,我不認爲它提供了一個選項來導出表格時轉換表格。此外,我的目標實際上是在Powerpoint演示文稿中使用此表格。你推薦從R到Powerpoint(或同等)導出表的最直接的方式是什麼? – fstevens

+0

@fstevens我不能說。我避免了像瘟疫一樣的PowerPoint,並且通常建議其他人也這樣做。 – joran

+0

你推薦什麼? LateX/Beamer? – fstevens

2

另一種方式時:

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

我同意@joran R不打算排版漂亮的表格。

+0

非常好的解決方案,我認爲 – fstevens

0

您可以複製的屬性,以恢復表格形式:

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

如果你想避免額外的名稱,下面的代碼這樣做,雖然它是難以閱讀:

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