Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending % sign in output of prop.table

Tags:

r

sweave

I'm trying to append % sign in the output of prop.table to use in Sweave. My attempted code is below:

m <- matrix(1:4,2)
dimnames(m) <- list(c("A", "B"), c("C", "D"))
prop.table(m,1)*100

         C        D
A 25.00000 75.00000
B 33.33333 66.66667


paste(round(prop.table(m,1)*100, 3), "%", sep = "")
[1] "25%"     "33.333%" "75%"     "66.667%"


paste(sprintf("%.1f", prop.table(m,1)*100), "%", sep = "")
[1] "25.0%" "33.3%" "75.0%" "66.7%"

Using paste will change the class from matrix to character. I'd highly appreciate if someone guide me the right solution. Thanks

like image 399
MYaseen208 Avatar asked Feb 07 '12 23:02

MYaseen208


2 Answers

Another solution could be replacing content of matrix:

m2 <- m
m2[] <- sprintf("%.1f%%",round(prop.table(m,1)*100, 3))
m2
#   C       D      
# A "25.0%" "75.0%"
# B "33.3%" "66.7%"
like image 189
Marek Avatar answered Oct 14 '22 18:10

Marek


Most functions designed to work with vectors also accept matrices but return a vector instead of a matrix: paste, sprintf, etc. You can use apply, that will return a matrix.

apply( 
  prop.table(m,1)*100, 
  2, 
  function(u) sprintf( "%.1f%%", u ) 
)
like image 20
Vincent Zoonekynd Avatar answered Oct 14 '22 19:10

Vincent Zoonekynd