Appending % sign in output of prop.table

后端 未结 4 490
囚心锁ツ
囚心锁ツ 2021-01-12 07:42

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)
dimnam         


        
相关标签:
4条回答
  • 2021-01-12 08:07

    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 ) 
    )
    
    0 讨论(0)
  • 2021-01-12 08:08

    There's a package called janitor that takes care of the prop.table() "format-as-percentage" problem. Here's a link to the package: https://github.com/sfirke/janitor

    Here's a usage example from the github page.

    roster %>%
      tabyl(employee_status, full_time) %>%
      adorn_totals("row") %>%
      adorn_percentages("row") %>%
      adorn_pct_formatting() %>%
      adorn_ns() %>%
      adorn_title("combined")
    #>  employee_status/full_time         No        Yes
    #>             Administration   0.0% (0) 100.0% (1)
    #>                      Coach 100.0% (2)   0.0% (0)
    #>                    Teacher  33.3% (3)  66.7% (6)
    #>                      Total  41.7% (5)  58.3% (7)
    
    0 讨论(0)
  • 2021-01-12 08:16

    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%"
    
    0 讨论(0)
  • 2021-01-12 08:25

    This is an extension of the answer from @VincentZoonekynd that adds margins (totals for rows/columns) and removes the double quotes:

    library(magrittr)
    
    m %>%
      prop.table %>%
      addmargins %>%
      apply(MARGIN=2, FUN=scales::percent, accuracy=0.1) %>%
      noquote
    
    #>     C     D     Sum   
    #> A   10.0% 30.0% 40.0% 
    #> B   20.0% 40.0% 60.0% 
    #> Sum 30.0% 70.0% 100.0%
    
    0 讨论(0)
提交回复
热议问题