Adding% sign to prop.table output

I am trying to add the% sign to the output of prop.table for use in Sweave . My code was below:

 m <- matrix(1:4,2) dimnames(m) <- list(c("A", "B"), c("C", "D")) prop.table(m,1)*100 CD 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 would really appreciate if anyone would give me the right solution. Thanks

+6
source share
2 answers

Most functions designed for working with vectors also accept matrices, but return a vector instead of a matrix: paste , sprintf , etc. You can use apply , which will return the matrix.

 apply( prop.table(m,1)*100, 2, function(u) sprintf( "%.1f%%", u ) ) 
+5
source

Another solution could be to replace the contents of the matrix:

 m2 <- m m2[] <- sprintf("%.1f%%",round(prop.table(m,1)*100, 3)) m2 # CD # A "25.0%" "75.0%" # B "33.3%" "66.7%" 
+8
source

Source: https://habr.com/ru/post/907892/


All Articles